Skip to content
Advertisement

With VueJS Cli how should do to have a variable common to all pages and be able to watch it in a page

I’m relatively new to VueJs and I’m stuck on a project and I can’t find a solution online.

I want to have a variable commun to all pages (month), and when that variable change I want to be able to do something on my page.

Example of what I want to do (simplified)

In App.vue

JavaScript

In Home.vue or any other page

JavaScript

But since the variable is changed on the app.vue, (no matter what page I’m on) I can’t watch it on my page.

Do you know how I should do? What is the best practice for that kind of stuff?

Thanks in advance if someone can help me!

EDIT: SOLVED

State Management and $emit did the trick. While discovering Vuex I found out that my app didn’t need such a big state manager so I’ve found another way (based on the same idea):

I’ve created a bus.js with an empty Vue instance:

JavaScript

Then in my component I use

JavaScript

And on my pages :

JavaScript

Advertisement

Answer

Component based UI frameworks like Vue, React, and friends enforce the idea of passing data down into components (Props in Vue) but not allowing those components to pass updates to that data up to parents by simply changing the data. The reason for this is performance; making data changes explicitly allows the framework to only re-render when it needs to.

Instead of updating props that have been passed into a component, updates can be passed up with events or by using a state manager like Vuex.

If you’re looking for a simple way to achieve this, check out $.emit : https://v2.vuejs.org/v2/api/#vm-emit

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement