Vue简单实用请访问https://blog.csdn.net/weixin_51497206/article/details/117510658?spm=1001.2014.3001.5501
本文主要讲述vuex模块化使用
为什么要使用模块化?
模块化使用是为了让合作开发更方便,不容易产生git冲突,也是为了让项目代码更清晰合理,便于管理。
另外就是命名空间的问题,就是为了让当前vuex模块里的状态名,函数名不和其他的空间相冲突,但是调用时要加上模块名
1.打开vue项目目录下的src文件夹中的store文件夹,新建一个文件夹modules,modules中新建一个DD.js(命名随意)
此时store中index.js代码如下
import Vue from "vue";
import Vuex from "vuex";
import DD from "./modules/DD"; //引入新建的module
import createPersistedState from "vuex-persistedstate"; //此处为引入vuex数据持久化插件
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
//Module是store分割的模块,每个模块拥有自己的state、getters、mutations、actions。
DD, //使用新建的module
},
plugins: [
createPersistedState({
storage: window.sessionStorage, //默认存入localStorage,此处为存入sessionStorage
}),
],
});
DD.js如下
export default {
state: {
//存储的数据
token: "",
name: "1",
},
mutations: {
setToken(state, token) {
//更改state存储的数据
state.token = token;
},
setName(state, name) {
state.name = name;
},
},
actions: {
//actions触发mutations中的方法
tokenFun({ commit }, token) {
commit("setToken", token);
},
nameFun({ commit }, name) {
commit("setName", name);
},
},
namespaced: true, //让本模块成为带命名空间的模块。
};
打开需要使用vuex的页面,我这里在home.vue里边写了
启动项目,页面效果如下
home.vue代码如下
<template>
<div class="home">
<div @click="click">
{{ name }}
{{ token }}
</div>
</div>
</template>
<script>
// @ is an alias to /src
import { mapActions, mapState } from "vuex"; //引入辅助函数
export default {
name: "Home",
computed: {
//计算属性中引入vuex模块中的属性
...mapState("DD", ["name", "token"]),
//第一个参数为引入模块名,数组中参数为模块中的state
},
methods: {
...mapActions("DD", ["tokenFun", "nameFun"]),
//第一个参数为引入模块名,数组中参数为模块中的actions
click() {
this.tokenFun("token"); //括号里的是要存的值
this.nameFun("name"); //括号里的是要存的值
},
},
};
</script>
点击页面中的1,页面变动为
以上即为全部内容