vue----webpack模板----vuex----modules子模块
modules模块
modules:模块
作用 将所有的数据进行模块的拆分 而不是放在一个store里面,拆分后有利于管理 注意在每个小模块导出的时候一定要加命名空间 namespaced=true 这样就不会出现命名冲突 如果想要调用小模块里面的方法 则需要加上小模块的名称 例如 handleAdd:"goodsStore/handleAdd"
子模块文件夹设置
store
index.js(主模块)
goodsStore(商品模块)
state.vue
actions.vue
mutations.vue
getters.vue
index.vue
总模块的设置store/index.js
import Vue from "vue"; import Vuex from "vuex"; //引入子仓库 import goodsStore from "./goodsStore"; Vue.use(Vuex); const state = { } const mutations = { } const actions = { } const getters = { } const store = new Vuex.Store({ state, mutations, actions, getters, modules:{ goodsStore } }) export default store;
子模块设置
goodsStore/state.js export default{ } goodsStore/mutations.js export default{ } goodsStore/actions.js export default{ } goodsStore/getters.js export default{ } goodsStore/index.js //导入 import state from "./state" import mutations from "./mutations" import actions from "./actions" import getters from "./getters" export default{ //独立的命名空间 namespaced:true, state, mutations, actions, getters }
组件中使用子模块中的state中的数据和actions中的方法
<template>
<div class="home">
<h1>{{message}}</h1>
</div>
</template>
<script>
import Vuex from "vuex";
export default {
data(){
return{
}
},
watch:{
},
computed:{
...Vuex.mapState({
inputVal1:state=>state.inputVal1,
inputVal2:state=>state.inputVal2,
//使用子模块中的数据
message:state=>state.goodsStore.message
}),
...Vuex.mapGetters({
//不允许写函数
sum:"sum"
})
},
methods:{
...Vuex.mapActions({
handleChange:"handleChange",
//使用小模块中的方法
handeleAdd:"goodsStore/handleAdd"
})
}
}
</script>
<style>
</style>

浙公网安备 33010602011771号