vue.js 2 how to watch store values from vuex

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

    You can use a combination of Vuex actions, getters, computed properties and watchers to listen to changes on a Vuex state value.

    HTML Code:

    JavaScript Code:

    'use strict'
    
    Vue.use(Vuex)
    
    const { mapGetters, mapActions, Store } = Vuex
    
    new Vue({
        el: '#app',
      store: new Store({
        state: {
          color: 'red'
        },
        getters: {
          color({color}) {
            return color
          }
        },
        mutations: {
          setColor(state, payload) {
            state.color = payload
          }
        },
        actions: {
          setColor({commit}, payload) {
            commit('setColor', payload)
          }
        }
      }),
      methods: {
        ...mapGetters([
            'color'
        ]),
        ...mapActions([
            'setColor'
        ])
      },
      computed: {
        computedColor: {
            set(value) {
            this.setColor(value)
          },
          get() {
            return this.color()
          }
        },
        style() {
            return `background-color: ${this.computedColor};`
        }
      },
      watch: {
        computedColor() {
            console.log(`Watcher in use @${new Date().getTime()}`)
        }
      }
    })
    

    See JSFiddle demo.

提交回复
热议问题