Vuex实践-mapState和mapGetters

本文是Vuex系列的最后一篇,详细介绍了如何在多模块环境中使用mapState和mapGetters访问state和getters。通过示例展示了在App.vue和Index.vue组件中,如何通过不同方式引用不同模块的state和getters,并强调了命名空间配置的重要性。同时,文中指出mapGetters只能通过字符串形式访问getters。最后,文章提醒注意state和getters的命名避免冲突。
摘要由CSDN通过智能技术生成

一.前言

  本文章是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\

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值