vuex 当存储的值发生变化时执行方法
时间: 2023-07-28 15:51:00 浏览: 49
在 Vuex 中,可以使用 `watch` 函数来监听 state 中的值的变化,当值发生变化时,执行相应的方法。具体实现步骤如下:
1. 在组件中引入 `Vuex` 和需要使用的 state 和 mutation。
2. 使用 `watch` 函数监听需要的 state 的变化。
3. 在回调函数中执行相应的 mutation。
示例代码如下:
```javascript
// 在组件中引入 Vuex 和需要使用的 state 和 mutation
import { mapState, mapMutations } from 'vuex'
export default {
computed: {
...mapState({
count: state => state.count
})
},
methods: {
...mapMutations({
increment: 'increment'
})
},
created() {
// 使用 watch 函数监听 count 的变化
this.$store.watch(
state => state.count,
(newVal, oldVal) => {
// 在回调函数中执行相应的 mutation
this.increment(newVal)
}
)
}
}
```
上述代码中,当 `count` 值发生变化时,会执行 `increment` mutation。这里使用了 `mapState` 和 `mapMutations` 函数来简化代码,如果不熟悉这两个函数的使用,可以查阅 Vuex 官网文档。