vuex 当存储的值发生变化时执行方法 请给我一个完整示例
时间: 2024-03-25 08:37:16 浏览: 17
好的,以下是一个完整的示例:
store.js:
```javascript
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state, payload) {
state.count += payload
}
},
actions: {
incrementAsync({ commit }, payload) {
setTimeout(() => {
commit('increment', payload)
}, 1000)
}
}
})
```
App.vue:
```vue
<template>
<div class="container">
<h1>Count: {{ count }}</h1>
<button @click="incrementCount">Increment</button>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
computed: {
...mapState({
count: state => state.count
})
},
methods: {
...mapMutations({
increment: 'increment'
}),
incrementCount() {
this.increment(1)
}
},
created() {
this.$store.watch(
state => state.count,
(newVal, oldVal) => {
console.log(`Count changed from ${oldVal} to ${newVal}`)
}
)
}
}
</script>
```
在上述示例中,我们创建了一个 Vuex store,其中包含一个 `count` state 和一个 `increment` mutation。在 `App.vue` 组件中,我们使用了 `mapState` 和 `mapMutations` 函数来简化代码。在 `created` 钩子函数中,我们使用了 `$store.watch` 函数来监听 `count` 值的变化,当 `count` 值发生变化时,会执行回调函数并输出变化信息到控制台。
当我们点击按钮时,会触发 `incrementCount` 方法,该方法会调用 `increment` mutation 将 `count` 值加 1。此时,`$store.watch` 函数会监听到 `count` 值的变化并执行回调函数,输出变化信息到控制台。
希望这个示例对你有所帮助。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)