Vuex.Store中的state和mutations
时间: 2024-03-10 09:46:39 浏览: 27
在Vuex.Store中,state是用来存储数据的对象,mutations是用来修改state中数据的方法。state中的数据可以被组件通过this.$store.state来访问,而mutations中的方法可以被组件通过this.$store.commit来调用。下面是state和mutations的详细介绍:
1. state
state是Vuex.Store中用来存储数据的对象,它包含了应用程序中所有需要管理的状态。state中的数据可以被组件通过this.$store.state来访问。例如,你可以在Vuex.Store中定义一个名为`count`的state,代码如下:
```javascript
const store = new Vuex.Store({
state: {
count: 0
}
})
```
在这个例子中,我们在state中定义了一个名为`count`的变量,初始值为0。组件可以通过`this.$store.state.count`来访问这个变量。
2. mutations
mutations是Vuex.Store中用来修改state中数据的方法,它们必须是同步函数。mutations中的方法可以被组件通过`this.$store.commit`来调用。例如,你可以在Vuex.Store中定义一个名为`increment`的mutation,代码如下:
```javascript
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
```
在这个例子中,我们定义了一个名为`increment`的mutation,它将state中的`count`变量加1。组件可以通过`this.$store.commit('increment')`来调用这个mutation。
mutations中的方法也可以接收额外的参数,例如:
```javascript
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state, amount) {
state.count += amount
}
}
})
```
在这个例子中,我们定义了一个名为`increment`的mutation,它将state中的`count`变量加上额外的`amount`参数。组件可以通过`this.$store.commit('increment', 10)`来调用这个mutation,将`amount`参数设置为10。
mutations中的方法还可以被异步调用,但是异步操作不能直接修改state中的数据。如果需要在异步操作中修改state中的数据,可以使用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)