vuex中开启命名空间如何读取state,操作state
时间: 2023-07-19 13:44:30 浏览: 47
在 Vuex 中,如果开启了命名空间,那么在读取和操作 state 时需要注意一些变化。
读取 state:
如果开启了命名空间,那么在读取 state 时,需要使用 `mapState` 辅助函数来将 state 映射到组件的计算属性中。同时,在 `mapState` 函数中需要传递命名空间的名称。
例如,假设有一个名为 `moduleA` 的命名空间,其中有一个名为 `count` 的 state,那么可以通过以下方式来将 `count` 映射到组件的计算属性中:
```javascript
import { mapState } from 'vuex'
export default {
computed: {
...mapState('moduleA', {
count: state => state.count
})
}
}
```
在上面的代码中,使用了 `mapState` 辅助函数将 `moduleA` 命名空间下的 `count` 映射到了组件的计算属性中,这样就可以通过 `this.count` 来访问该 state 了。
操作 state:
如果需要操作 state,那么需要使用 `dispatch` 和 `commit` 方法,并在调用时传入命名空间的名称。
例如,假设有一个名为 `moduleA` 的命名空间,其中有一个名为 `increment` 的 mutation,那么可以通过以下方式来触发该 mutation:
```javascript
// dispatch
this.$store.dispatch('moduleA/increment')
// commit
this.$store.commit('moduleA/increment')
```
在上面的代码中,在调用 `dispatch` 和 `commit` 方法时,需要在命名空间名称前加上模块的名称和一个斜杠 `/`,即 `moduleA/`,这样就可以正确地触发该 mutation 了。
需要注意的是,在使用 `dispatch` 和 `commit` 方法时,如果要传递参数,那么需要将命名空间的名称放在第一个参数的位置,例如:
```javascript
this.$store.dispatch('moduleA/incrementAsync', {
amount: 10
})
```
在上面的代码中,调用了 `moduleA` 命名空间下的名为 `incrementAsync` 的 action,并传递了一个名为 `amount` 的参数。