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

<div id="app">
    <div id="topBar">
      <div id="nav">
        <div><router-link to="/">Home</router-link></div>
        <div><router-link to="/expenses">Dépenses</router-link></div>
        <div><router-link to="/revenues">Revenus</router-link></div>
        <div><router-link to="/category">Categories</router-link></div>
      </div>
    </div>
    <select name="selectMonth" v-model="month" id="selectMonth" required>
        <option v-for="(month, index) in months" :key="index" :value=month>{{ month }}</option>
    </select>
    <router-view/>
  </div>

In Home.vue or any other page

watch: {
    month: function () {
      this.getExpenses() // or something else (In this case I want to fetch data again with a new month)
    }
  },

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:

import Vue from 'vue'
const bus = new Vue()

export default bus

Then in my component I use

import bus from '../bus'

... 

onChangeMonth () {
      bus.$emit('new-month', this.month)
    },

And on my pages :

import bus from '../bus'

...

created () {
    bus.$on('new-month', this.getExpenses)
  },

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