vue.js 2 how to watch store values from vuex

后端 未结 18 2128
傲寒
傲寒 2020-11-27 10:26

I am using vuex and vuejs 2 together.

I am new to vuex, I want to watch a store variable change.

I want t

相关标签:
18条回答
  • 2020-11-27 10:46

    It's as simple as:

    watch: {
      '$store.state.drawer': function() {
        console.log(this.$store.state.drawer)
      }
    }
    
    0 讨论(0)
  • 2020-11-27 10:46

    if you use typescript then you can :

    import { Watch } from "vue-property-decorator";
    
    ..
    
    @Watch("$store.state.something")
    private watchSomething() {
       // use this.$store.state.something for access
       ...
    }

    0 讨论(0)
  • 2020-11-27 10:47

    Inside the component, create a computed function

    computed:{
      myState:function(){
        return this.$store.state.my_state; // return the state value in `my_state`
      }
    }
    

    Now the computed function name can be watched, like

    watch:{
      myState:function(newVal,oldVal){
        // this function will trigger when ever the value of `my_state` changes
      }
    }
    

    The changes made in the vuex state my_state will reflect in the computed function myState and trigger the watch function.

    If the state my_state is having nested data, then the handler option will help more

    watch:{
      myState:{
        handler:function(newVal,oldVal){
          // this function will trigger when ever the value of `my_state` changes
        },
        deep:true
      }
    }
    

    This will watch all the nested values in the store my_state.

    0 讨论(0)
  • 2020-11-27 10:48

    The best way to watch store changes is to use mapGetters as Gabriel said. But there is a case when you can't do it through mapGetters e.g. you want to get something from store using parameter:

    getters: {
      getTodoById: (state, getters) => (id) => {
        return state.todos.find(todo => todo.id === id)
      }
    }
    

    in that case you can't use mapGetters. You may try to do something like this instead:

    computed: {
        todoById() {
            return this.$store.getters.getTodoById(this.id)
        }
    }
    

    But unfortunately todoById will be updated only if this.id is changed

    If you want you component update in such case use this.$store.watch solution provided by Gong. Or handle your component consciously and update this.id when you need to update todoById.

    0 讨论(0)
  • 2020-11-27 10:53

    Let's say, for example, that you have a basket of fruits, and each time you add or remove a fruit from the basket, you want 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:

    • Computed properties and watchers
    • API docs: computed
    • API docs: watch
    0 讨论(0)
  • 2020-11-27 10:53

    You could also subscribe to the store mutations:

    store.subscribe((mutation, state) => {
      console.log(mutation.type)
      console.log(mutation.payload)
    })
    

    https://vuex.vuejs.org/api/#subscribe

    0 讨论(0)
提交回复
热议问题