210 Namespacing Modules

为了避免不同模块之间的状态、 mutations、actions 和 getters 命名冲突,Vuex 模块可以使用命名空间(namespaced: true)。这样可以确保在访问模块的状态和方法时,需要使用特定的命名空间路径。比如,调用一个命名空间为 “user” 的模块中的 action,可能需要使用

dispatch('user/login')而不是直接使用dispatch('login')

示例

创建带命名空间的模块

const moduleA = {
  namespaced: true,
  state: {
    // 模块 A 的状态
  },
  mutations: {
    // 模块 A 的 mutations
  },
  actions: {
    // 模块 A 的 actions
  },
  getters: {
    // 模块 A 的 getters
  }
};

访问命名空间中的状态和方法

1、使用mapStatemapMutationsmapActionsmapGetters辅助函数时,需要指定模块的命名空间。

import { mapState, mapMutations, mapActions, mapGetters } from 'vuex';

export default {
  computed: {
    // 映射模块 A 的状态
   ...mapState('moduleA', {
      moduleAState: state => state.moduleA.stateProperty,
    }),
    // 或者使用对象展开运算符更简洁的写法
   ...mapState('moduleA', {
      moduleAState: 'moduleA/stateProperty',
    }),
  },
  methods: {
    // 映射模块 A 的 mutations
   ...mapMutations('moduleA', {
      moduleAMutation: 'moduleA/mutationMethod',
    }),
    // 映射模块 A 的 actions
   ...mapActions('moduleA', {
      moduleAAction: 'moduleA/actionMethod',
    }),
    // 映射模块 A 的 getters
   ...mapGetters('moduleA', {
      moduleAGetter: 'moduleA/getterMethod',
    }),
  },
};

2、直接使用$store访问命名空间模块的状态和方法时,需要使用命名空间路径。

this.$store.dispatch('moduleA/actionMethod', payload);
this.$store.commit('moduleA/mutationMethod', payload);
const stateValue = this.$store.state.moduleA.stateProperty;
const getterValue = this.$store.getters['moduleA/getterMethod'];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄健华Yeah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值