1、首先在store文件下创建modules文件夹,在内部新建各个模块的js文件
文件内部写法如下:
const oneVuex={ namespaced: true, state:{ oneCount:100, oneNum:50 }, actions:{ oneAcAdd({commit},oneVal){ commit('oneMuAdd',oneVal) }, oneAcMinus({commit},oneVal){ commit('oneMuMinus',oneVal) } }, mutations:{ oneMuAdd(state,oneVal){ state.oneNum+=oneVal }, oneMuMinus(state,oneVal){ state.oneNum-=oneVal } } } export default oneVuex
截图:
2、在store内创建除modules文件夹外的getters.js以及index.js,分别存储计算属性以及总体数据
getters内写法:
const getters={ changeState(state){ return state.oneVuex.oneNum/4 } } export default getters
3、index.js内部写法:
import Vuex from "vuex"; import Vue from "vue"; import oneVuex from "./modules/oneVuex" import twoVuex from "./modules/twoVuex" import getters from './getters' Vue.use(Vuex); const store=new Vuex.Store({ modules:{ oneVuex, twoVuex }, getters, }) export default store
截图:
4、组件内部使用
<template> <div> <h2>home</h2> <h3>vuex中的oneNum:{{oneNum}}</h3> <h3>vuex中的twoNum:{{twoNum}}</h3> <h3>vuex中的changeState:{{changeState}}</h3> <button @click="oneAcAdd(10)">home改变</button> </div> </template> <script> import {mapState, mapGetters, mapActions} from "vuex" export default { name: "Home", data() { return { }; }, created() { }, computed:{ ...mapState('oneVuex',{ oneNum:state=>state.oneNum }), ...mapState('twoVuex',{ twoNum:state=>state.oneNum }), ...mapGetters({ changeState:'changeState' }) }, methods: { ...mapActions('oneVuex',{ oneAcAdd:'oneAcAdd' }), }, }; </script>
截图: