Software
Is there any way to have multiple Vues have a computed listener working on the same value?
Setup:
I have multiple Vue components, and each component has multiple instances in different dialogs in my web app.
For each type of component I have a global state so that each type of component stays in sync across the dialogs.
I'd like for it so that when a component proceeds beyond step 1, I hide the other components in that dialog.
I have achieved this nicely using the computed / watch combo.
However, my problem is that it seems if I try to listen in with computed through more than 1 Vue instance, it hijacks the other listeners.
Problem
Below is a simplified version of what I'm working with, when the app starts up, the console logs 'computed 1' & 'computed 2'. But then when I change handrailOptions.step, only the second fires. ('computed 2' & 'watched 2')
Is there any way to have multiple Vues have a computed listener working on the same value?
var checkoutDialog = new Vue({ el: '#dialog-checkout', computed: { newHandrailStep() { console.log('computed 1'); return handrailOptions.step; } }, watch: { newHandrailStep( test ) { console.log('watched 1'); } } }); new Vue({ el: '#dialog-estimate-questions', computed: { newHandrailStep() { console.log('computed 2'); return handrailOptions.step; } }, watch: { newHandrailStep( test ) { console.log('watched 2'); } } });how to route dynamically in store.js file in vue
I have a function in store.js (vuex), that check some conditions, if satisfies, it should initiate route to another component.
this.$router.push() is not working in store.js .
Neither vm.$router.push() is working ,here vm = new Vue() .
Websocket onmessage event doesnt update component data
I am setting my callbacks in mounted:
data() { return { code: 'Apple', } }, mounted() { console.log(this.code) // prints 'Apple' this.$options.sockets.onopen = this.wsOpen(); this.$options.sockets.onmessage = this.logMessage(msg); }, methods: { logMessage(msg){ this.code += "\n" + msg.data; console.log("this.code: " + this.code); }, }However it is telling me that 'msg' is not defined. The following works, however this.code becomes out of scope:
this.$options.sockets.onmessage= function (msg) { console.log(msg.data) // this works, msg is not undefined here console.log(this.code) // doesnt work, this.code is undefined }I think im doing something dumb.
Pass a variable in an array, not a value in javascript
is there a way to pass a variable itself, not a value in javascript? I remember being able to do so in flas as3 if i remember correct which was based on javascript. I'm not sure why i can't do the same here. Your help would be much appreciated.
variable1: false, function1() { this.variable1 = true //this works of course console.log(this.variable1) prints true } function2() { var temparray1 = [this.variable1] temparray1[0] = true //does not work like i want, it's the value in the array that change, not this.variable1 console.log(this.variable1) //prints still false console.log(temparray1[0]) //prints true }Vue js data attribute not updating after click event?
I've created a vue component for a sorting icon, for tables etc.
The idea being a user can click on the icon to change the sorting (A->Z , Z->A)
<template> <i class="mdi mdi-sort" aria-hidden="true" @click.prevent="sort()" :class="{active: (active == name), desc: (orderDir == 'DESC')}"> </i> </template> <script> export default { props: { name: { required: true }, active: { required: false, }, eventName: { required: true, } }, data() { return { orderDir: "DESC", } }, methods: { /** * Fire a sort event with details of the field name and the direction to be sorted */ sort() { console.log(this.orderDir); if (this.orderDir === "DESC") { this.orderDir = "ASC"; } else { this.orderDir = "DESC"; } console.log(this.orderDir); EventBus.fire(this.eventName, { "name": this.name, "direction": this.orderDir }); } }, } </script>The issue is with the sort() method, which during execution does not seem to update the orderDir property.
Console Output
------ First click
DESC
ASC
------ Second click
DESC
ASC
The expectation is that second time around the orderDir value should be already set to "ASC" and would be reverted back to "DESC".
I think I am missing out something obvious?
VueJS nested component doesn't update property on action
This example of the official guide works properly (of course).
Then I tried by my own by making it a component, it also works.
But once nested in a parent component, the message can not be reversed, and I can't figure out why.
Vue.component('todo-item', { props: ['todo'], template: '<div>' + '<li>{{ todo.text }}</li>' + '<button v-on:click="reverseMessage">Reverse Message</button>' + '</div>', methods: { reverseMessage: function () { var reversed = this.todo.text.split('').reverse().join(''); console.log('tried with ' + reversed); this.todo.text = reversed; } } });Here is the JSFiddle : https://jsfiddle.net/37y1ukjh/
How to structure a multi-page website with Vue on each page
I'm trying to use Vue on my first multi-page website and don't know how to split my code across pages. Let's say I have a "master" template which contains the headers and footer + 3 pages, Home, About and Contact.
If I have a single Vue instance in the master template I think I will need to have all the code for every page in that instance.
If I have a separate instance for each page then what do I do about shared code, e.g. a button in the header which launches a popup?
I can't really use Vue components with their own templates because all the pages have to have their HTML on page when it loads for SEO reasons (using asp.enet Umbraco CMS)
$router redefine and Vue.use(Vuex) should be called only once
My project created by webpack template!!;
npm run build online it can work well, but the vendor.js is too big!
modified webpack config webpack.prod.conf.js add this:
js externals: { 'vue': 'Vue', 'vee-router': 'VueRouter', 'vuex': 'Vuex', },
i separated the vue,vue-router,vuex , include by CDN ! like:
```html
<body> <div id="app"></div> <!-- built files will be auto injected --> <script src="https://unpkg.com/vue@2.3.4/dist/vue.js"></script> <script src="https://unpkg.com/vue-router@2.3.1/dist/vue-router.js"></script> <script src="https://unpkg.com/vuex@2.3.1"></script> </body>```
but when i upload the file to line, some problems like:
vuex@2.3.1:667 [vuex] already installed. Vue.use(Vuex) should be called only once. vendor.js:24 Uncaught TypeError: Cannot redefine property: $router at Function.defineProperty () at Function.v [as install] (vendor.js:24) at Function.Vue.use (vue.js:4110) at Object. (vendor.js:24) at r (manifest.js:1) at Object. (app.js:1) at r (manifest.js:1) at Object. (app.js:1) at r (manifest.js:1) at Object. (app.js:1)
can someone help me?
Set a boolean from buttonGroup (vue-strap)
I try to use the component buttonGroup from the library vue-strap as a toggle but I can't get it work. I succeed to set string value but not boolean value.
Here is the code
<button-group v-model="radioValue" type="primary"> <radio selected-value="true">Correct</radio> <radio selected-value="false">Incorrect</radio> </button-group>The variable radioValue is updated correctly and set to "true" or "false" (string). But now I'd like to set a boolean instead (true or false).
I tried to make a codepen but I can't get it work neither. If it was working, I would tell you to open the console and execute vm.radioValue, click on Incorrect and execute vm.radioValue a second time. You will see that a string is set instead of a boolean.
I tried to bind the value (:select-value="true"). It kind of work but when the user clic on "Correct", the other button (Incorrect) is also active. Maybe it's a bug from vue-strap...
Read Json file from <input> in front end [on hold]
I want to read a file got from an <input> on the front end, in order to parse it (it will be a json file). Im working on a webpack application using javascript with vue.js.
I've tried readFile or rawFile objects but it did't worked...
What can i do please ?
Thx.
how to change page title according to route links vuejs
I want to change my page title according to the links I follow, just like how every page on stack overflow all have different page title with different links, some page titles are binded with the question title, how can such be done with vuejs, this will be good for search engine optimization, etc. I'm loving vuejs but I dont understand this part, is there something I'm missing?
Updating a chart from chart.js in vue
I have a function in my vue applications that creates a chart.This is the chart function:
startChart: function (canvas, type) { // init chart.js var ctx = document.getElementById("myChart"); var myDoughnut = new Chart(ctx, { type: 'doughnut', data: { labels: this.getAnalyticList[this.getRowIndex].chartNames, datasets: [{ data: this.getAnalyticList[this.getRowIndex].chartData, backgroundColor: [ 'rgba(255, 99, 132, 0.6)', 'rgba(54, 162, 235, 0.6)', 'rgba(255, 206, 86, 0.6)', 'rgba(75, 192, 192, 0.6)', 'rgba(153, 102, 255, 0.6)', 'red', 'yellow', 'blue', 'green', 'orange', 'teal', 'violet', 'pink', 'purple' ] }] }, options: { responsive: true, defaultFontColor: '#ffffff', } }) }and i then started it in the vue mounted hook using this line
this.startChart(this.$refs.canvas, 'Doughnut');What i want to do is take the row index of a table loaded above the chart and that would then be passed into the getAnalyticList value that loads the charts so i can grab different arrays from the same list. I was working on creating an update function i got off this js fiddle from this stack article. I've been trying to adapt the function he created into vue but am having no luck here is the function:
changeData: function () { var myChart = Chart.doughnut(this.$refs.canvas, { data: data, }); myChart.data.datasets.data = this.getAnalyticList[this.getRowIndex].chartData; myChart.data.labels = this.getAnalyticList[this.getRowIndex].chartNames; myChart.update(); }Any suggestions would be appreciated.
Vue scope: how to delay handling of @mouseover
So I want to have an action only if the user has the mouse on the div for at least 1 second. Inside template:
<div @mouseover="trigger"></div>Inside script:
data() { return { hovered: false } } methods: { trigger() { setTimeout(function(){ this.hovered = true }, 1000) } }My problem is that I don't understand the scope of Vue. Because this.hovered is inside another function, it does not find the actual hovered data variable. What's the solution to this?
How can I re-run Vue.js ApolloClient middleware?
In my main.js I have some code that checks for the existence of a localStorage item. If it has it, it will add an Authorization header via middleware to the ApolloClient setup.
However, if a localStorage item is later added, it's not present in the middleware of main.js. A full page refresh is therefore required in order to get it to pick it up / know of its existence.
How can I run main.js again (if that's even the solution) from a method in say, a component that signs the user in?
Here's my main.js:
import Vue from 'vue' import ApolloClient, { createNetworkInterface } from 'apollo-client' import VueApollo from 'vue-apollo' import App from './App' import router from './router' import store from './store' const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/MY-ID-HERE' }) const requestToken = localStorage.getItem('TOKEN') networkInterface.use([{ applyMiddleware (req, next) { if (!req.options.headers) { req.options.headers = {} } req.options.headers['Authorization'] = requestToken ? `Bearer ${requestToken}` : null next() } }]) const apolloClient = new ApolloClient({ networkInterface }) const apolloProvider = new VueApollo({ defaultClient: apolloClient }) Vue.use(VueApollo) /* eslint-disable no-new */ new Vue({ el: '#app', template: '<App />', components: { App }, apolloProvider, router, store })Hopefully you can understand what I'm trying to do?
Thanks
VueJs + Firebase
I'm starting to use VueJS with Firebase (and VueFire), but I'm starting to struggle a bit about how to structure the data.
My case is pretty simple.
I have a list of suppliers and a list of products.
A product can only be linked to one supplier, and a supplier can have multiple products.
And I have different views :
- List of all products for all suppliers
- List of products for one supplier
- Detail of one product with the supplier.
For the 1st and 2nd views, I have no issue with the following structure
products - productKey1 - name : Product1 - productKey2 - name : Product2 supplier-products: - supplierKey1 - productKey1 - name : Product1 - supplierKey2 - productKey2 - name : Product2 supplier: - supplierKey1 - name : Supplier1 - supplierKey2 - name : Supplier2I can easily show a list of all products from "/products" and for each supplier from "supplier-products/supplierKey"
But what about a view with the product detail + the supplier detail.
What is the best way to do that ?
- Adding the supplier information into each products ?
- Add a kind of foreign key into products ?
- Another way to do it ?
Thanks for your help.
While passing data from parent to child, it passes but view doesn't get updated
I have a a root and a child component. I am trying to pass data using the props from parent to child.
<div id="root"> <my-component> v-bind:valObj='valObjItems'> </my-component> </div> Vue.component('money-manager-section', { props: ['accountTypes'], data() { return { accounts: Object.assign({},this.accountTypes) } }, template: ` <div v-for="x in accounts"></div> // I kept it short for this line. It returns 0 ` }Through Vue debugger extension, I can see my-component has the accountTypes but id doesn't show.
The object structure is like this:
var obj = { 1 : { "a", "z", "k", "m" } 2 : { "a", "b", "c", "d" } }And in my main app,
var app = new Vue({ el: '#root', data: { accountTypes : {}, }, // And these are what I use for push and delete: methods : { pushValue(key, value) { var obj = this.accountTypes if (obj.hasOwnProperty(key)) { var idx = $.inArray(value, obj[key]); if (idx == -1) { obj[key].push(value); } } else { obj[key] = [value]; } }, removeFromArray(key, val) { var idx = $.inArray(val, this.accountTypes[key]); if (idx != -1) { this.accountTypes[key].splice(idx, 1); } } }Set input[text] value according to radio button
I'm trying to set the value of an input corresponding to the selected radio button, but I just can't figure out how.
<input type="text" class="input" name="provider" v-model="selected_provider"> <b-radio-group v-model="provider_options"> <div class="field"> <template v-for="provider in providers"> <b-radio name="select_provider[]" id="provider_@{{ $index }}" model="selected_provider" value="provider" type="radio"> @{{ provider.provider_name }} </b-radio> </template> </div> </b-radio-group>I've managed to get an array to display and that the input shows whatever is written in selected_provider, but I just don't know how to link those together.
var app = new Vue({ el: '#app', data: { selected_provider: '', providers: [ { provider_name: 'Twitch', provider_url: 'https://www.twitch.tv/' }, { provider_name: 'Smashcast', provider_url: 'https://www.smashcast.tv/' }, { provider_name: 'AzubuFrost', provider_url: 'https://www.smashcast.tv/' } ] }, });furthermore I'd like to attach the value of
<input type="text" class="input" name="name" id="name">to the end of provider_url in selected_provider
Is someone so kind to help me?
Vue.js Use mounted in v-for
I want to run a method inside a v-for in my Vue component. Example:
<div v-for="(foo,index) in bar> <p>{{myMethod(foo,index)}}</p> </div>When I do this the p-tag just stays empty. Here is my method:
myMethod:function(foo,index){ //do something with foo and index return SomethingWithFooAndIndex }When I alert( SomethingWithFooAndIndex), the browser is showing exactly what I need. So do you guys have any idea why the p tag stays empty?
Thanks!
Vuejs - How to get global variable in store mutation
I am getting error about using vue-i18n dependance.
How should i get the const i18n from main.js to root.js (store)
I am using
- Vuejs 2.X
- Vue-i18n latest
- Vuex For Vuejs 2.X
In main.js (vue-cli)
Vue.use(VueI18n) const i18n = new VueI18n({ locale: 'en', messages: { en: { message: en }, cn: { message: cn } } }) new Vue({ store, el: '#app', i18n, router, template: '<App/>', components: { App } })In root.js (store)
export const mutations = { [types.SET_LANGUAGE] (state, data) { console.log(i18n.locale) // 'i18n' is not defined localStorage.setItem('language', data) }, }Vuex + Typescript
I am converting a JavaScript project to TypeScript. However I am getting a type error when trying to make Vue use Vuex.
import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex);It looks like the problem is that vuex does not provide type definitions like vuejs does?
Because I also have to set
"allowSyntheticDefaultImports": truein my tsconfig.json.
How can I solve this problem and make Vue.use accept Vuex as the correct type?