- 创建命名空间
- mian.js
- src/store/index.js
- src/store/getters.js
- src/store/modules 各自管理仓库
- src/store/modules/testVuexModules.js 命名空间模块
- 组件内提交与获取Vuex的值:
- 1.异步操作 this.$store.dispatch
- 2.同步操作 this.$store.commit
创建命名空间
mian.js
import Vue from "vue";
import store from "./store";new Vue({el: "#BYUI_APP",router,store,render: (h) => h(App),
});
src/store/index.js
import Vue from "vue";
import Vuex from "vuex";
import getters from "./getters";Vue.use(Vuex);
const modulesFiles = require.context("./modules", true, /\.js$/);
const modules = modulesFiles.keys().reduce((modules, modulePath) => {const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");const value = modulesFiles(modulePath);modules[moduleName] = value.default;return modules;
}, {});
const store = new Vuex.Store({ modules, getters });
export default store;
src/store/getters.js
const getters = {// testVuexModules: 对应命名空间的模块名phone: (state) => state.testVuexModules.phone,address: (state) => state.testVuexModules.address,// arrList(名字自取): "testVuexModules"模块的映射集,方便获取state的值arrList:(state) => {return state.testVuexModules},
};
export default getters;
src/store/modules 各自管理仓库
src/store/modules/testVuexModules.js 命名空间模块
const state = {address: '',phone: '',
};const mutations = {CHANGE_INFO: (state, info) => {state.address = info.address;state.phone = info.phone;// 如果想状态不想因为浏览器刷新而丢失,可以将状态缓存到本地// localStorage(数据永久缓存在本地浏览器中) sessionStorage(临时缓存,有时效)// 两者使用方式一致,区别在时效localStorage.setItem("GET_PHONE", state.phone)// 移除缓存localStorage.removeItem('GET_PHONE')},
};const actions = {changeInfo({ commit }, info) {commit("CHANGE_INFO", info);},
};
// 添加namespaced:true的方式使其成为带命名空间的模块
export default { namespaced: true, state, mutations, actions };
组件内提交与获取Vuex的值:
1.异步操作 this.$store.dispatch
//提交数据: testVuexModules:模块名, changeInfo: action方法名
this.$store.dispatch("testVuexModules/changeInfo", this.form)//获取状态方式 1:对应getters.js的getters对象
this.$store.getters.address//获取状态方式 2:当需要获取多个state状态,可以通过映射集,减少代码量,增加美观性
//辅助函数mapGetters批量使用状态, arrList: 对应getters.js的属性arrList
import { mapGetters, mapState } from "vuex"
// computed
computed: {...mapGetters(["arrList"]),
},// 获取数据
this.arrList.phone
2.同步操作 this.$store.commit
// 提交数据: testVuexModules(模块名), CHANGE_INFO(mutations方法名)
// 注意: 此提交方式需在 namespaced 开启 true 才会生效
this.$store.commit("testVuexModules/CHANGE_INFO", this.form)// 获取状态方式 1
this.$store.state.testVuexModules.phone// 获取状态方式 2
import { mapGetters, mapState } from "vuex"// computed
computed: {...mapGetters(["arrList"]),...mapState({getMapState: (state) => state.testVuexModules,}),
},// 获取数据
this.getMapState.phone
获取缓存的值
localStorage.getItem("GET_PHONE")