vue.js 2 how to watch store values from vuex vue.js 2 how to watch store values from vuex vue.js vue.js

vue.js 2 how to watch store values from vuex


Let's say, for example, that you have a basket of fruits,and each time you add or remove a fruit from the basket, youwant to (1) display info about fruit count, but you also (2) want to be notified of the count of the fruits in some fancy fashion...

fruit-count-component.vue

<template>  <!-- We meet our first objective (1) by simply -->  <!-- binding to the count property. -->  <p>Fruits: {{ count }}</p></template><script>import basket from '../resources/fruit-basket'export default () {  computed: {    count () {      return basket.state.fruits.length      // Or return basket.getters.fruitsCount      // (depends on your design decisions).    }  },  watch: {    count (newCount, oldCount) {      // Our fancy notification (2).      console.log(`We have ${newCount} fruits now, yay!`)    }  }}</script>

Please note, that the name of the function in the watch object, must match the name of the function in the computed object. In the example above the name is count.

New and old values of a watched property will be passed into watch callback (the count function) as parameters.

The basket store could look like this:

fruit-basket.js

import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)const basket = new Vuex.Store({  state: {    fruits: []  },  getters: {    fruitsCount (state) {      return state.fruits.length    }  }  // Obviously you would need some mutations and actions,  // but to make example cleaner I'll skip this part.})export default basket

You can read more in the following resources:


It's as simple as:

watch: {  '$store.state.drawer': function() {    console.log(this.$store.state.drawer)  }}


You should not use component's watchers to listen to state change. I recommend you to use getters functions and then map them inside your component.

import { mapGetters } from 'vuex'export default {  computed: {    ...mapGetters({      myState: 'getMyState'    })  }}

In your store:

const getters = {  getMyState: state => state.my_state}

You should be able to listen to any changes made to your store by using this.myState in your component.

https://vuex.vuejs.org/en/getters.html#the-mapgetters-helper


matomo