vue2 vuex模块化设计

vue2 vuex模块化设计

为了方便vuex使用,简单进行vuex的模块化设计,这里仅仅针对vue2,vue3有更简单的pinia,本身就是按照模块化进行的设计,因此不讨论。

项目环境:vue-cli 5.0.4(需要查看cli版本直接终端输入 vue --version 即可), webpack是vue-cli内置打包工具,node 16.15.0。

vuex模块化的文件结构:
vue2 vuex模块化设计_第1张图片

入口文件index.js

实现步骤:

  1. 安装Vuex
  2. 创建Vuex.store实例
  3. 导出Vuex.store实例,并在main.js中挂载

代码:

import Vue from 'vue';
import Vuex from 'vuex';
// 引入store模块
import userStore from './modules/userStore';
// 安装Vuex
Vue.use(Vuex);
// 创建Vuex.store实例
export default new Vuex.Store({
    state: {},
    actions: {},
    mutations: {},
    modules: {
        userStore
    }
});

store模块文件

代码实现:

// 登录用户信息的store模块
export default {
    namespaced: true,
    state: {
        username: 'linda',
        password: '123456'
    },
    actions: {},
    mutations: {
        updateUsername(state, obj) {
            state.username = obj.username;
            state.password = obj.password;
        }
    }
};

注意:

  1. 导出的模块文件是对象,而且 namespaced: true 属性是必须要设置, 作用是避免多个模块的命名相同。
  2. mutation 里面执行同步操作, actions 里面执行异步操作。
  3. 每个模块的命名空间名最好和文件名同名,方便管理。

.vue组件中使用store

  1. .vue组件内使用store的属性和方法,可以在vuex中导出 mapState, mapActions, mapActions的辅助方法既可(具体怎么使用可以看官网文档), 这些方法的都需要放到计算属性中触发,第一个参数时可选的命名空间名,获取的属性或者方法通过数组包裹即可, 具体示例如下:
    vue2 vuex模块化设计_第2张图片
    当然,如果仅仅是为了读取state里面的属性,可以直接使用this.$store.state.命名空间名.属性名称 即可读取,mapState的函数也只在这个方法基础上进行封装简化,其它辅助方法同理。

你可能感兴趣的:(vue.js,webpack,前端)