vuex中使用modules时遇到的坑

其实也不算坑,只是自己没注意看官网api,定义module另外命名时,需要在module中加一个命名空间namespaced: true

属性,否则命名无法暴露出来,导致报[vuex] module namespace not found in mapState()等错误。

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Vuex的模块化结构可以更好地组织和管理应用程序的状态。以下是使用Vuex模块的步骤: 1. 创建一个模块对象,包含该模块的状态、mutation、action和getter: ```javascript const myModule = { state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }, getters: { doubleCount (state) { return state.count * 2 } } } ``` 2. 在store注册模块,使用`modules`选项: ```javascript import Vuex from 'vuex' const store = new Vuex.Store({ modules: { myModule } }) ``` 3. 在组件使用模块的状态、mutation、action和getter: ```javascript import { mapState, mapMutations, mapActions, mapGetters } from 'vuex' export default { computed: { // 获取模块状态 ...mapState({ count: state => state.myModule.count }), // 获取模块的getter ...mapGetters('myModule', { doubleCount: 'doubleCount' }) }, methods: { // 触发模块的mutation ...mapMutations('myModule', { increment: 'increment' }), // 触发模块的action ...mapActions('myModule', { incrementAsync: 'incrementAsync' }) } } ``` 在上面的示例,我们使用`mapState`、`mapMutations`、`mapActions`和`mapGetters`辅助函数来访问模块的状态、mutation、action和getter。这些辅助函数会自动将模块的名称添加到对应的方法名,以便正确地访问模块。这样,我们就可以在组件使用模块的状态和方法,而无需手动编写长长的命名空间前缀。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值