Software
How can I disable back button on the browser with vue component?
My vue component like this :
<template> <span class="rating"> ... </span> </template> <script> export default { props: { 'star': null }, ... } </script>If the component is running I want to disable button back in the browser. So the user can not go back to the previous page
How can I do it?
Webpack with babel-loader not emitting valid es5
I have a webpack config that is based off https://github.com/vuejs-templates/webpack-simple/blob/master/template/webpack.config.js It uses vue-loader and babel-loader. The issue is I cannot get it to generate ES5 code so that it will work in the most broad range of clients.
If I use the ES2015 preset, webpack.optimize.UglifyJsPlugin fails to minify the output because Uglify can only handle ES5 (not counting the harmony branch). The errors are similar to: Unexpected token: punc (() and occur in multiple files.
I can work around this by using babili-webpack-plugin which will minify the ES6 code but is very slow. However, when I deploy this code, I see errors being reported back saying Block-scoped declarations (let, const, function, class) not yet supported outside strict mode so I know they are older clients choking on ES6 code.
How can I get proper ES5 code output from babel-loader? I have tried multiple presets, with or without the transform-runtime plugin. Config below:
const webpack = require('webpack'); const globEntries = require('webpack-glob-entries'); const _ = require('lodash'); const path = require('path'); const BabiliPlugin = require("babili-webpack-plugin"); const env = process.env.NODE_ENV; let entries; if (env === 'production') { entries = globEntries('./src/**/vue/*.js'); } else { entries = _.mapValues(globEntries('./src/**/vue/*.js'), entry => [entry, 'webpack-hot-middleware/client?reload=true']); } module.exports = { entry: entries, output: { path: '/', ///no real path is required, just pass "/" publicPath: '/vue', filename: '[name].js', }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { scss: 'vue-style-loader!css-loader!sass-loader', sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax', }, // other vue-loader options go here }, }, { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', query: { presets: ['es2015'], plugins: ['transform-runtime'], }, }, }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]', }, }, ], }, resolve: { alias: { vue$: 'vue/dist/vue.esm.js', }, }, plugins: [ new webpack.HotModuleReplacementPlugin(), // Enable HMR new webpack.NoEmitOnErrorsPlugin(), ], performance: { hints: false, }, devtool: '#eval-source-map', }; if (env === 'staging' || env === 'production') { //module.exports.devtool = env === 'staging' ? '#source-map' : false; module.exports.devtool = '#source-map'; module.exports.output.path = path.resolve(__dirname, './src/v1/parse/cloud/public/vue'); // http://vue-loader.vuejs.org/en/workflow/production.html module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: `"${env}"`, }, }), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, compress: { warnings: false, }, }), // new BabiliPlugin(), new webpack.LoaderOptionsPlugin({ minimize: true, }), ]); }Vue.js data value not updating when adding new value
When new bars value are set, the data is not updated. Please check below;
I'm planning to do dynamic bars and buttons. Once the buttons are clicked, the new values will be updated to bars values.
Here is the link
HTML
<h1><span>Vue.js</span> Progress Bar</h1> <div id="app"> <div v-for="(index, bar) in bars" class="shell"> <div class="bar" :style="{ width: bar + '%' }" .> <span>{{ bar }}%</span> <input type="radio" id="radio-bar" value="{{ index }}" v-model="picked" v-on:change="set(index)"> </div> </div> <span v-for="(index, button) in buttons"> <button value="{{ button }}" @click.prevent="makeProgress(button)">{{ button }}</button> </span> <br> <p>Selected Bar: {{ picked }}</p> <p>Button Value: {{ buttonVal }}</p> </div>JS
var dataURL = 'http://pb-api.herokuapp.com/bars'; var vm = new Vue({ el: "#app", data: { maxColor: "#F22613", bars: [], buttons: [], limit: 0, selectedBar: 0, buttonVal: 0 }, methods: { fetchData: function(params) { this.$http.get(dataURL, function(data) { this.$set('bars', data.bars); this.$set('buttons', data.buttons); this.$set('limit', data.limit); console.log(params); }); }, set: function(index) { this.selectedBar = index; }, makeProgress: function(button) { var self = this; self.buttonVal += button; this.reachMax(); Vue.set(this.bars, 0, 55); }, reachMax() { if(this.buttonVal >= this.limit){ alert('Reached Limit' + this.limit) } } }, created: function() { this.fetchData(); } });axios set headers in config vue js
Right now I use axios like this:
import axios from 'axios' axios.get(apiObjUrl, { headers: { 'Content-type': 'application/x-www-form-urlencoded', } }) .then(({data}) => {How do I set global axios header? (I need to set localization header to use in all my requests)
Laravel Vue SPA vs SSR
Many laravel/vue tutorials use ajax calls to get the data. It seems that the SPA is completely isolated from Laravel. I.e. Laravel is just a data API and the vue app could also simply be hosted on a third party external server (e.g. AWS S3). Is this the recommended way, or should I rather use Laravel for Routing and have separate views that implement individual components and already included data instead of using a SPA?
insert tab pages inside v-ons-tabbar
Here's my component.
<template> <v-ons-page> <v-ons-tabbar :visible="true" :tabs="tabs" position="top"> </v-ons-tabbar> </v-ons-page> </template> <template id="pendingPage"> <v-ons-page> <p>pending items</p> </v-ons-page> </template> <template id="completedPage"> <v-ons-page> <p>completed items</p> </v-ons-page> </template> <script> import Vue from 'vue'; const pendingPage = { template: '#pendingPage' }; const completedPage = { template: '#completedPage' }; export default { data() { return { activeIndex: 0, tabs: [ { label: 'Pending', page: pendingPage }, { label: 'Completed', page: completedPage } ] }; } }; </script>Expected: I expect my component to render two tabs - Pending & Completed.
Problem: It only renders completedPage.
What I am doing wrong here?
How access Vue Js computed properties?
I have the next code with vuejs, i call axios method post and set the authenticated user correctly(cosole show the user), but when i call the computed property in the component the user is empty
export default { data() { return { isAuth: null, } }, computed: { authenticatedUser () { return this.getAuthenticatedUser() } }, created() { this.isAuth = this.$auth.isAuthenticated() this.setAuthenticatedUser() }, methods: { setAuthenticatedUser () { axios.get('/api/user') .then(response => { this.$auth.setAuthenticatedUser(response.data) console.log(this.$auth.getAuthenticatedUser()) }) }, getAuthenticatedUser(){ return this.$auth.getAuthenticatedUser() } }, router }And this my code for get the authenticated user
export default function (Vue) { let authenticatedUser = {}; Vue.auth = { //set token setToken (token, expiration) { localStorage.setItem('token', token) localStorage.setItem('expiration', expiration) }, //get token getToken() { var token = localStorage.getItem('token') var expiration = localStorage.getItem('expiration') if( !token || !expiration) return null if(Date.now() > parseInt(expiration)){ this.destroyToken() return null } else{ return token } }, //destroy token destroyToken() { localStorage.removeItem('token') localStorage.removeItem('expiration') }, //isAuthenticated isAuthenticated() { if(this.getToken()) return true else return false }, setAuthenticatedUser(data){ return authenticatedUser = data; }, getAuthenticatedUser(){ return authenticatedUser; }, } Object.defineProperties(Vue.prototype, { $auth: { get() { return Vue.auth } } }) }When i not use the computed property

When i use the computed property in the model

Append array inside object using $set
I have an object and the structure looks like this
obj: { 1: { 'a': [ [] ], 'b': [ [] ] } }Now, in watcher, I am trying to append 'c' => [ [] ] to this object.
I tried using this.obj[key]['c'] = [ [] ], but it doesn't watch changes on the props when I do it this way. I am almost sure that I need to use $set
this.$set(this.obj, key, { ['c']: [ [] ] }) - using this actually watches it, however it removes 'a' and 'b' properties entirely.
What is the proper way of using $set
(vuejs)this.$router.go() doesn't work in safari of iOS 10.3.2 only
It's works fine in Android's broswer or iPhone's Safari with other versions of iOS. But in 10.3.2, doesn't jump to target page.
Vue.js routing with Express
I've created a portfolio here https://temp-portfolio.herokuapp.com. My issue is that when a user refreshes a page other than index.html or goes straight to another link such as https://temp-portfolio.herokuapp.com/projects the routing doesn't render. I've set up everything using Node.js and Express on Heroku following this guide https://medium.com/@sagarjauhari/quick-n-clean-way-to-deploy-vue-webpack-apps-on-heroku-b522d3904bc8.
I tried rewriting the server to this https://stackoverflow.com/a/44226999/4178637 but the app crashes.
server.js
var express = require('express'); var path = require('path'); var serveStatic = require('serve-static'); app = express(); app.use(serveStatic(__dirname)); var port = process.env.PORT || 5000; app.listen(port); console.log('server started '+ port);index.js
import Vue from 'vue' import Router from 'vue-router' import Nav from '@/components/Nav' import Home from '@/components/Home' import Projects from '@/components/Projects' import Urban from '@/components/Urban' import Seizure from '@/components/Seizure' import Explosion from '@/components/Explosion' import Decadence from '@/components/Decadence' import Threshold from '@/components/Threshold' Vue.use(Router) Vue.component('app-nav', Nav) export default new Router({ routes: [ { path: '/', name: 'Home', component: Home }, { path: '/projects', name: 'Projects', component: Projects }, { path: '/projects/urban', name: 'Urban', component: Urban }, { path: '/projects/seizure', name: 'Seizure', component: Seizure }, { path: '/projects/explosion', name: 'Explosion', component: Explosion }, { path: '/projects/decadence', name: 'Decadence', component: Decadence }, { path: '/projects/threshold', name: 'Threshold', component: Threshold } ], mode: 'history' })main.js
import Vue from 'vue' import App from './App' import router from './router' import './assets/styles/styles.scss' Vue.config.productionTip = false new Vue({ el: '#app', router, template: '<App/>', components: { App } })Can't access data variable inside watcher, inside .map()
My root looks like this. I have defined types and history variables inside data and in watch, I am trying to access another variable rather than the one I am watching. Trying to access history variable outside .map() works however using it inside .map() returns undefined
new Vue({ el: '#root', data: { types: {}, history: {} } watch: { types: { handler(obj) { console.log(this.history) // works types.map(function(val) { console.log(this.history) // undefined }) } } } }Cannot access other data values inside watch
In my root, i have a setup like this,
new Vue({ el: '#root', data: { types: {}, history: {} } watch: { types: { handler(obj) { console.log(this.history) // gives me undefined } } } }this.history throws undefined even though it is initialised as an empty object in data. Also, in this watcher, I can not use my methods inside methods: {}, it also says undefined.
However, if I do $vm0.history in my console, it doesn't say undefined.
What is the proper way of achieving this?
vue js: How get parent id in directive (eg v-if)
How get id from class="video" and use in directive v-if?
Should my Vue.js code have multiple small instances or a single big instance?
I'm starting with vue.js. My question is about design patterns.
Should I have multiple Vue instances like this one:
var example = new Vue({ el: '#post-list', data: { posts: [ { title: 'Foo' }, { title: 'Bar' } ] } }); var example2 = new Vue({ el: '#post-list2', data: { posts: [ { title: 'Foo' }, { title: 'Bar' } ] } });Or should I try to group my Vue code inside a big #app element like this:
var app= new Vue({ el: '#app', data: { posts1: [ { title: 'Foo' }, { title: 'Bar' } ], posts2: [ { title: 'Foo' }, { title: 'Bar' } ] } });I'm looking for code maitenance and performance. What are the advantages of each approach? Is there a better pattern to follow?
vue js reuse of 3d.js
New to Vue js (using version 2).
I would like to reuse the bubble-chart project in vue js. It has allot of goodies inside like 3D.js and some jQuery but it's ok for me for now (not being Vue js).
I understand that one way is to create parallel component of Vue js from scratch.
What is the correct way to import/reuse none Vue projects?
Dynamic number of inputs
I have problem with dynamic number of radio input in array like that
Color:<br> <label><input type="radio" name="params[54]" value="21">Blue</label> <label><input type="radio" name="params[54]" value="38">Yellow</label> Size:<br> <label><input type="radio" name="params[12]" value="32">S</label> <label><input type="radio" name="params[12]" value="44">M</label> <label><input type="radio" name="params[12]" value="58">L</label>It could not be only Color and Size and it shoud have more than two or three inputs. I use VueJS Component.
export default { data () { return { params: {} } }, methods:{ update: function(){ // here I want use params } } }I need watch change input and get params object witch one are selected like:
{ 54: 21, 12: 44 }I seriously don't know how can I do this. Any ideas?
How to integrate Node.js running on different port with Vue.js running on a different port altogether?
I have a local Node.js server running on port 3000. I have another dev server for front end using webpack, running on 8080. Node is connected to MySQL server. I want to send data from my Node to front end. My project structure looks like this:-
SampleProject -> BackEnd -> FrontEndShould I use CORS node module? If not how should I send the data?
Update component
I am missunderstanding how to update a component. So, here is the HTML :
<div id="app"> <form v-on:submit="submitForm"> <input type="text" id="txtSearch"> <input type="submit" value="go"> </form> <br><br> <user></user> </div>And the JS :
let userComponent = { template: 'your name is : {{name}}<br>You are {{age}}' }; let vueApp = new Vue({ el: '#app', components: {'user': userComponent}, methods: { submitForm: function(e) { e.preventDefault(); let val = document.getElementById('txtSearch').value; alert('submitted : ' + val); // normally i do a search here : let result = mySearch(val); // but let's do the job with this : let result = {name: 'John', age: 27}; // so now, how to modify the <user> with this data result ? } } });So, my aim is to create a template, and of course update his data. How to do this ? I created a jsfiddle for testing : https://jsfiddle.net/4w0kh30t/1/ Thanks for your help.
Vue.js and Vue-Resource Status 404 on Delete HTTP Request with json-server
i'm working on a sandbox project using Vue.js, Vue-resource, Vuex and json-server. I succeed to use the GET request with Vue-resource to display all my Customers but when i'm trying to remove a selected customer, the console show me a 404 error.
Here the error
Can you help me to resolve this issue please ? Thanks :D
Here my Vuex store :
import Vue from 'vue' import Api from '../../../lib/Api' export default{ state: { customers: [], profiles: [], }, actions: { getCustomers({commit}) { Vue.http.get(Api.getCustomersUrl(), {}).then((response) => { commit('loadCustomers', response.data); }) }, getCustomerProfile({commit}, id) { Vue.http.get(Api.getCustomerProfile(id), {}).then((response) => { commit('loadCustomerProfile', response.data); }) }, deleteCustomerProfile({commit}, id) { Vue.http.delete(Api.getCustomerProfile(id), {}).then((response) => { }, (response) => { console.log('erreur', response) }) }, removeAllProfile({commit}) { Vue.http.delete(Api.getCustomersUrl(), {}).then((response) => { }) } }, mutations: { loadCustomers(state, customers) { state.customers = customers }, loadCustomerProfile(state, profiles) { state.profiles = profiles }, removeCustomerProfile(state, profiles) { state.profiles = profiles }, removeAllCustomerProfile(state, customers) { state.customers = customers } }, }Here my customers component :
<div class="customers-list"> <div class="customers-list__content"> <img :src="customer.photo" @click.self="selectProfile"> <p>{{customer.first_name}}</p> <p>{{customer.last_name}}</p> <p>{{customer.jobTitle}}</p> <p>{{customer.email}}</p> <p>{{customer.company}}</p> </div> </div> </div> </template> <script> export default{ props: ['customer'], methods:{ selectProfile() { this.$store.dispatch('getCustomerProfile', this.customer.id) console.log(this.customer.id); }, removeAll(){ this.$store.dispatch('removeAllProfile') } }, } </script>Here my selected customer component :
<template> <div> <img :src="profile.photo"> <p>{{profile.first_name}}</p> <p>{{profile.last_name}}</p> <p>{{profile.jobTitle}}</p> <p>{{profile.email}}</p> <p>{{profile.company}}</p> <p>{{profile.id}}</p> <i class="fa fa-trash-o" aria-hidden="true" @click.self="deleteProfile"></i> </div> </template> <script> import {mapState} from 'vuex' export default{ props:['profile'], methods: { deleteProfile(){ this.$store.dispatch('deleteCustomerProfile', this.profile.id); console.log(this.profile.id); }, }, } </script>And here my Homepage to display all my content with a v-for directive :
<div class="home"> <h1>Hello, world !</h1> <div class="home__forms"> <input type="text" v-model="firstname" placeholder="first name"> <input type="text" v-model="lastname" placeholder="last name"> <input type="text" v-model="jobTitle" placeholder="job"> <input type="text" v-model="email" placeholder="email"> <input type="text" v-model="company" placeholder="company"> <input type="text" v-model="photo" placeholder="photo"> <button @click="submit">Add</button> </div> <div class="customers"> <customers-list v-for="(customer, index) in customers" :customer="customer" :key="customer.id"></customers-list> </div> <profile v-for="(profile, index) in profiles" :profile="profile" :key="profile.id"></profile> </div> </template> <script> import {mapState} from 'vuex' import CustomersList from './CustomersList.vue' import Customer from './Customer.vue' export default{ components: { 'customers-list': CustomersList, 'profile': Customer, }, data() { return{ firstname: "", lastname:"", jobTitle:"", email: "", company: "", photo:"", error: false, } }, computed: mapState({ customers: state => state.test.customers, profiles: state => state.test.profiles, }), methods:{ submit(){ var self = this; if(this.email === "" || this.firstname === "" || this.lastname ==="" || this.jobTitle === "" || this.company === "" || this.company === "" || this.avatar === "") { this.error =true } else { this.$http.post(process.env.API_URL + '/customers', { first_name: this.firstname, last_name: this.lastname, jobTitle: this.jobTitle, email: this.email, photo: this.photo, company: this.company }).then((response) => { self.error = false }, () => { self.error = true }); console.log("submitted"); } } }, created(){ this.$store.dispatch('getCustomers') }, } </script>Have a good day !
Vue2+Foundation, Getting error in their integration
I am integrating Vue2 and Foundation-sites, I keep getting this error Refused to load the font 'https://sxt.cdn.skype.com/assets/fonts/SkypeAssets-Regular.woff' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.
Kindly Help!!
