mutations actions实例
时间: 2024-05-10 11:18:28 浏览: 17
以下是一个 Vuex store 中使用 mutations 和 actions 的示例:
```javascript
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
},
decrement(state) {
state.count--
}
},
actions: {
increment(context) {
context.commit('increment')
},
decrement(context) {
context.commit('decrement')
}
}
})
```
在上面的代码中,我们定义了一个名为 `count` 的状态,并定义了两个 `mutations`:`increment` 和 `decrement`,它们分别用于增加和减少 `count` 的值。
同时,我们也定义了两个 `actions`:`increment` 和 `decrement`,它们分别用于触发 `mutations` 中的 `increment` 和 `decrement` 方法。在这里,我们使用了 `context` 参数来调用 `commit` 方法来触发对应的 `mutation`。
通过这种方式,我们可以将状态的变更逻辑封装在 `mutations` 中,而将异步请求、多个 `mutation` 的一起执行等操作封装在 `actions` 中,使代码更加清晰和易于维护。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)