vuex store 分模块化
store分模块代码如下所示:
代码结构下图所示
// user.js 模块 const user = { state: { demo: '我是XX用户' }, //同步 this.$store.commit('方法名'); 来调用 mutations: { setDemo(state, value) { state.demo = value + " 触发demo"; }, setDemo1(state, value) { state.demo = value + " 触发demo1"; } }, //异步 this.$store.dispatch('方法名'); 来调用 actions: { //this.$store.dispatch('setName'); setName(content) { console.log("走这里了setName") content.commit('setDemo', ""); }, // 这里使用了异步 setName1(content, value) { console.log("走这里了setName1") content.commit('setDemo1', value); } } }; export default user;
// getters.js
const getters = { demo: state => state.user.demo } export default getters;
// index.js
import Vue from 'vue' import Vuex from 'vuex' import getters from './getters' Vue.use(Vuex) //module文件夹下太多文件,导入太麻烦,使用context实现模块化导入 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
// main.js中引入 import App from './App.vue' import Vue from 'vue' Vue.config.productionTip = false App.mpType = 'app' import store from './store/index' // 引入 //把vuex定义成全局组件 Vue.prototype.$store = store // 挂载 const app = new Vue({ ...App, store // 挂载 }) app.$mount()
// 页面测试用例代码
<template> <viw> <view class="content">sotre 测试</view> <view>{{ this.$store.state.user.demo }}</view> <button @click="test" style="width: 90%;">点我【commit提交】</button> <button @click="test2" style="width: 90%;margin-top: 30px;">点我【dispatch提交】</button> </viw> </template> <script> import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'; export default { data() { return { title: 'Hello' }; }, computed: mapState(['user']), // 这里是引用user模块 mounted() { console.log(this.$store.getters.demo); console.log('我是doemo2:' + this.$store.state.user.demo); }, onLoad() {}, methods: { ...mapMutations(['setDemo']), ...mapActions(['setName']), test() { this.$store.commit('setDemo', '大王加我来巡山-01'); }, test2() { //this.$store.dispatch('setName'); this.$store.dispatch('setName1', '大王加我来巡山-02'); } } }; </script>
文章属于个人工作备忘录,欢迎指正...