监听Vuex存储数据变化
方法1:
将state数据映射到组件的computed,然后监听映射的计算属性即可
// vuex 中的state数据
state: {
count: 0
},
// A 组件中映射 state 数据到计算属性
computed: {
getCount() {
return this.$store.state.count
}
}
// A 组件监听 count 计算属性的变化
watch: {
// watch 可以监听 data 数据也可以监听全局 vuex数据
getCount: {
handler(newVal, oldVal) {
this.count = newVal
},
deep: true,
immediate: true,
}
}
方法2:
vuex中store对象本身提供了watch函数
created() {
this.$store.watch((state,getters) => {
return state.count
},() => {
this.changeCount++
})
}
方法3
直接对vuex对象进行watch监听
watch: {
`$store.state.data.count`: {
handler(newVal,oldVal) {
console.log(newVal,oldVal)
},
immediate: true,
deep: true
}
}