vue.js 2 how to watch store values from vuex

后端 未结 18 2264
傲寒
傲寒 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:56

    This is for all the people that cannot solve their problem with getters and actually really need a watcher, e.g. to talk to non-vue third party stuff (see Vue Watchers on when to use watchers).

    Vue component's watchers and computed values both also work on computed values. So it's no different with vuex:

    import { mapState } from 'vuex';
    
    export default {
        computed: {
            ...mapState(['somestate']),
            someComputedLocalState() {
                // is triggered whenever the store state changes
                return this.somestate + ' works too';
            }
        },
        watch: {
            somestate(val, oldVal) {
                // is triggered whenever the store state changes
                console.log('do stuff', val, oldVal);
            }
        }
    }
    

    if it's only about combining local and global state, the mapState's doc also provides an example:

    computed: {
        ...mapState({
            // to access local state with `this`, a normal function must be used
            countPlusLocalState (state) {
              return state.count + this.localCount
            }
        }
    })
    

提交回复
热议问题