使用模块可以降低应用程序的复杂性。我以这种方式在我的项目中使用 vuex:
文件夹结构:
src
--components/ => folder
--store/ => folder
--App.vue
--main.js
让我们看看 main.js 文件:
import Vue from 'vue';
import App from './App.vue'
// Import the index.js file from the store folder
import store from '@/store/index';
new Vue({
store,
render: h => h(App)
}).$mount('#app')
现在让我们检查商店文件夹结构
store/
--index.js
--moduleA/ => folder
--moduleB/ => folder
store文件夹中的index.js文件
import Vue from 'vue';
import Vuex from 'vuex';
import moduleA from './moduleA'; // By default imports index.js file inside moduleA folder
import moduleB from './moduleB'; // By default imports index.js file inside moduleB folder
Vue.use(Vuex);
export default new Vuex.store({
modules: {
moduleA,
moduleB
}
});
最后,让我们创建我们的模块,moduleA文件夹结构(moduleB相同):
moduleA/ => folder
--index.js
--actions.js
--mutations.js
--getters.js
actions.js 文件:
function someAction({ commit }, payload) {
commit("someMutation", 'newValue');
}
export default {
someAction
}
mutations.js 文件:
function someMutation(state, payload) {
state.someStateVariable = payload;
}
export default {
someMutation
}
getters.js
export default {
getSomeStateVariable: state => state.someStateVariable
}
最后是 index.js 文件
import actions from './actions';
import getters from './getters'
import mutations from './mutations';
const state = {
someStateVariable: 'initial value'
}
export default {
actions,
getters,
mutations,
namespaced: true, // allows to use namespace in the components
state
}
对模块 B 重复,如果需要,对任何其他模块重复
我们已经准备好在我们的组件中使用 store 模块了:
<template>
<div>
{{ someStateVariable }}
<button @click="setAValue">Set a new value</button>
</div>
</template>
<script>
import { mapActions, mapGetters} from 'vuex';
export default{
name: "AComponent",
computed: {
...mapGetters({
// You can set any name as key, but the way to access the getter is
// with a string with the format "moduleName/getterName"
someStateVariable: "moduleA/getSomeStateVariable"
})
},
methods: {
...mapActions({
// Same as mapGetters
someAction: "moduleA/someAction"
}),
setAValue() {
// Actions within the mapActions helpers, can be accessed as local
// methods
this.someAction("A new value for the someStateVariable")
}
}
}
</script>
这是很多信息,我知道,所以如果有不清楚的地方,请告诉我,我会进一步解释。