一.前言
本文章是vuex系列的最后一篇,主要总结的是如何使用mapState和mapGetters访问vuex中的state和getters。
二.多个模块中mapState和mapGetters的使用
上一篇文章《Vuex实践(中)》里面我们总结的就是多模块的内容,所以关于store.js、moduleA.js和moduleB.js的代码保持不变。
在此为了方便观看,我将这三个文件的代码在贴在这里
E:\MyStudy\test\VueDemo\src\vuex\store.js
1 import Vue from 'vue' 2 import Vuex from 'vuex' 3 import moduleA from './moduleA' 4 import moduleB from './moduleB' 5 6 Vue.use(Vuex) 7 8 export default new Vuex.Store({ 9 state: { 10 counter: 1000 11 }, 12 mutations: { 13 //递增 14 increase(state) { 15 console.log("store-increase") 16 state.counter++ 17 }, 18 //递减 19 decrement(state) { 20 state.counter-- 21 } 22 }, 23 actions: { 24 increaseAction(context) { 25 setTimeout(function(){ 26 //action通过提交mutation改变共享数据状态 27 context.commit('increase'); 28 },3000) 29 }, 30 decrementAction(context){ 31 setTimeout(function(){ 32 //action通过提交mutation改变共享数据状态 33 context.commit('decrement'); 34 },3000) 35 } 36 }, 37 getters: { 38 doubleCounter(state) { 39 return state.counter*state.counter 40 } 41 }, 42 modules: { 43 a: moduleA, 44 b: moduleB 45 } 46 })
E:\MyStudy\test\VueDemo\src\vuex\moduleA.js
const moduleA = { namespaced: true, state:{ counter: 100 }, mutations: { //递增 increase(state) { console.log("moduleA-increase") state.counter++ }, //递减 decrement(state) { state.counter-- } }, actions: { increaseAction(context) { setTimeout(function(){ //action通过提交mutation改变共享数据状态 context.commit('increase'); },3000) }, decrementAction(context){ setTimeout(function(){ //action通过提交mutation改变共享数据状态 context.commit('decrement'); },3000) } }, getters: { doubleCounter(state) { return state.counter*state.counter } } } export default moduleA
E:\MyStudy\test\