【Vue学习】vuex modules 模块化

104 阅读2分钟

我正在参加「4月日新计划更文活动」,详情请看:4月日新计划更文活动

🦖我是Sam9029,一个前端

Sam9029的掘金主页:Sam9029的掘金主页

**🐱‍🐉🐱‍🐉恭喜你,若此文你认为写的不错,不要吝啬你的赞扬,求收藏,求评论,求一个大大的赞!👍**

使用的文件路径配置

  • 在状态仓库之中 使用一个单独的 index.js 文件 存放所有的仓库
  • 该文件 可以 只定义 modules 属性
- store 文件夹
    - index.js
    - modules
        - students.js
        - classes.js
        - teachers.js

index.js 文件配置

import vue from 'vue'
import vuex from 'vuex'
//引入仓库模块路径
import students from './modules/students.js'
import classes from './modules/classes.js'Vue.use(Vuex)
​
export default new Vuex.store({
    //state,getters,mutations,actions 可省略,如需用即写
    modules:{
        //引入仓库模块名称
        students,
        classes
    }
})

某一的状态机仓库配置 --- 以students.js为例子

  • 注意使用 namespaced:true, 属性//(重要)解决命名的冲突
export default {
    //(重要)解决命名的冲突
    namespaced:true,
    
    state:{},
    getters:{},
    mutations:{},
    actions:{}
}

调用 仓库 中的 数据 和 方法

在组件中使用时-辅助函数

1. 使用vuex 的store中单一的index文件的时候

在组件中,如果要使用 store 模块中的数据或方法,需要先引入辅助函数,然后在组件中对应的位置解构使用:

import { mapState, mapMutations } from "vuex";

2.使用vuex 的 modules (模块)的时候

在组件的引入,多引入一个函数

import { createNamespacedHelpers } from "vuex";
import { mapState, mapMutations, …… } = createNamespacedHelpers("对应的index文件里modules配置的模块名");
​
//实例
import { createNamespacedHelpers } from "vuex";
​
//⭐ 注意 组件使用多个模块时 解决命名冲突
// 解构重命名
import { 
    mapState:stuMapState, 
    mapMutations:stuMapMutations, 
    ……:…… } = createNamespacedHelpers("students");
​
import { 
    mapState:classMapState, 
    mapMutations:classMapMutations} = createNamespacedHelpers("classes");

注意

//⭐用在组件中 computed 接收

  • mapState 用于获取 state 的数据
  • mapGetters 用于获取 getters 的数据 ​ //⭐用在组件中 methods 接收
  • mapMutations 用于获取 mutations 的方法
  • mapAction 用于获取 actions 的方法

在组件 computed中调用辅助函数,获取对应的数据

computed: {
    //可以获取多个仓库中的数据
    ...mapState(["num"]),
    ...mapGetters(["num"]),
},

在组件 methods 中调用辅助函数,获取对应的方法

methods: {
    //可以获取多个仓库中的方法
    ...mapMutations(["methods"]),
    ...mapAction(["methods"]),
},

最后,在组件中就可以使用 拿到的数据和方法了:

<template>
    <div>
        <h2>计数器:{{ num }}</h2>
        <button @click="increment">+1</button>
    </div>
</template>


对比原本在组件里的的直接调用

  • 获取数据 $store.state.valueName
  • 获取方法 $store.commit('')

🦖我是Sam9029,一个前端

文章若有错误,敬请指正🙏

**🐱‍🐉🐱‍🐉恭喜你,都看到这了,求收藏,求评论,求一个大大的赞👍!不过分吧**

Sam9029的掘金主页:Sam9029的掘金主页