VUEX的Modules的使用

什么是Modules?

Modules是Vuex的核心概念之一,他的具体作用是分割store。个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割

在大型项目的时候需要模块化,这时候就得用Modules ,其中需要注意的是state的返回的是一个函数。

devtools:true/fals作用是让vue的调试工具不显示store

在分割出来的的模块局部状态,对于模块内部的mutation和getter,接受到的一个参数都是局部状态对象(state)但一状态数只有一个

namespaced:true, 在Modules切割的独立的组件中用来防止命名重复的 

createNamespacedHelpers  可以针对某一个模块专门针对的进行扩展

import { createNamespacedHelpers, mapState } from "vuex";

const { mapGetters: a } = createNamespacedHelpers("One");
  ...a({
      ac: "showC",
用法:  
1:<div>{{$store.getters['b/dds']}}</div> 
2:import {createNamespacedHelpers,mapState} from 'vuex'

const { mapGetters: a } = createNamespacedHelpers("One");
const {mapState:ba}= createNamespacedHelpers('One/a1')
3:computed:{
  ...a(['showC']),
  ...mapState({
    msg1:state=>state.One.a1.msg
  }),
  ...ba(['msg'])
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值