vue.js 2 how to watch store values from vuex

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

    If you simply want to watch a state property and then act within the component accordingly to the changes of that property then see the example below.

    In store.js:

    export const state = () => ({
     isClosed: false
    })
    export const mutations = {
     closeWindow(state, payload) {
      state.isClosed = payload
     }
    }
    

    In this scenario, I am creating a boolean state property that I am going to change in different places in the application like so:

    this.$store.commit('closeWindow', true)
    

    Now, if I need to watch that state property in some other component and then change the local property I would write the following in the mounted hook:

    mounted() {
     this.$store.watch(
      state => state.isClosed,
      (value) => {
       if (value) { this.localProperty = 'edit' }
      }
     )
    }
    

    Firstly, I am setting a watcher on the state property and then in the callback function I use the value of that property to change the localProperty.

    I hope it helps!

提交回复
热议问题