VueX 模块化和namespace

本文介绍了如何在VueX中实现模块化管理,通过划分不同功能的模块来组织state、actions、mutations,提高代码维护性。详细讲解了模块创建、注册、数据读取(state,getters)、dispatch和commit的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当我们的项目很大的时候,VueX中的代码会越来越多,会有处理数据的,处理人员列表的,处理订单的...

如果我们将这些东西都写在一个state、actions和mutations中的话,就非常不方便后期的维护。

所以我们引入了VueX的模块化的概念,每一个模块存储对应操作的数据和方法,方便后期的维护。

一、创建模块化

我们将不同功能区间组成不同的模块,每一个模块中都有与之对应的state, getters, actions, mutations。

{

        namespace:true,

        actions:{},

        mutations:{},

        state:{},

        getters:{}

}

我们也可以将一个模块放在一个js文件中进行暴露,然后在index.js中引入

二、注册模块

export default new VueX.Store({

        modules:{ 模块1, 模块2 }

})

三、读取模块中的数据

(一)读取state中的数据

1. 直接读取

this.$store.模块名.数据名

 

2. mapState读取

...mapState("模块名", ["数据1", "数据2"])

 

(二)读取getters中的数据

1. 直接读取

this.$store.getters["模组名 / 数据名"];

2. mapGetters读取

...mapGetters("模块名", ["数据1", "数据2"])

 

(三)调用dispatch

1. 直接读取

this.$store.dispatch("模块名 / 方法名", value)

2. mapActions读取

...mapActions("模块名",  {新方法名1 : "方法名1",  新方法名2 : "方法名2"})

 

(四)调用commit

使用方法和调用dispatch一致

1. 直接读取

this.$store.commit("模块名 / 方法名", value)

2. mapMutations读取 

...mapMutations("模块名",  {新方法名1 : "方法名1",  新方法名2 : "方法名2"})

在使用模块化Vuex 中,获取模块里面的值需要使用模块命名空间(module namespace)。 在定义模块时,可以通过 `namespaced: true` 开启模块命名空间,这样在获取模块内部的状态、getters、mutations、actions 时,就需要加上模块的命名空间。 举个例子,假设我们有一个 `user` 模块,其中定义了一个 `state`: ```javascript // user.js export default { namespaced: true, state: { name: '小明', age: 18 } } ``` 如果要在另一个模块中获取 `user` 模块的 `name` 值,可以这样写: ```javascript // other.js export default { computed: { userName() { return this.$store.state.user.name } } } ``` 但是在使用模块命名空间后,就需要添加模块命名空间前缀: ```javascript // user.js export default { namespaced: true, state: { name: '小明', age: 18 } } // other.js export default { computed: { userName() { return this.$store.state.user.name // 错误,需要加上模块命名空间前缀 // return this.$store.state['user'].name // 正确的方式 } } } ``` 如果需要在 getters、mutations、actions 中访问模块内部的状态其他函数,也需要加上模块命名空间前缀,例如: ```javascript // user.js export default { namespaced: true, state: { name: '小明', age: 18 }, getters: { getNameAndAge(state) { return `${state.name} - ${state.age}` } }, mutations: { setName(state, newName) { state.name = newName } }, actions: { changeName({ commit }, newName) { commit('setName', newName) } } } // other.js export default { computed: { nameAndAge() { return this.$store.getters['user/getNameAndAge'] // 获取 user 模块的 getters } }, methods: { changeName(newName) { this.$store.commit('user/setName', newName) // 调用 user 模块的 mutation this.$store.dispatch('user/changeName', newName) // 调用 user 模块的 action } } } ``` 以上就是在模块化 Vuex 中获取模块里面的值的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值