vue.js 2 how to watch store values from vuex

后端 未结 18 2265
傲寒
傲寒 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 11:10

    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

提交回复
热议问题