uni-app如何将vuex模块化
目录结构为
|---demo1.js
|---demo2.js
index.js
index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const context = require.context('./modules', false, /\.js$/);
const moduleStores = {};
context.keys().forEach(key => {
// 获取读取到的文件名字并且截取
const fileName = key.slice(2, -3);
//通过 context(key)导出文件内容
const fileModule = context(key).default;
moduleStores[fileName] = {
...fileModule,
};
});
export default new Vuex.Store({
modules: {
...moduleStores,
},
});
demo1.js
const demoname = {
fn: 'fn',
}
const store = {
state: {
demo: '名字'
},
getters: {
getLocale: state => {
return state.demo + 321
}
},
mutations: {
[demoname.fn]: (state, localeVal) => {
console.log('被执行了', localeVal)
}
},
actions: {
demoactions: ({ commit }, localeVal) => {
commit(demoname.fn, localeVal)
}
}
}
export default store
demo2.js同上
页面使用
<template>
<view class="content">
<view class="text-area">
<view class="title">{{demo1.demo}}</view>
<view class="title">{{getLocale}}</view>
</view>
</view>
</template>
<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
export default {
data() {
return {
title: 'Hello'
}
},
computed: {
...mapGetters(['getLocale']),
...mapState([
'demo1'
])
},
onLoad() {
this.fn('传递的内容')
this.demoactions('这是一个异步')
},
methods: {
...mapMutations([
'fn'
]),
...mapActions([
'demoactions'
])
}
}
</script>
<style>
</style>