vue.js - vuex2.0中,mapState和mapGetters的使用

查看:909
本文介绍了vue.js - vuex2.0中,mapState和mapGetters的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

为什么mapState获取不到组件对应的state值。代码中vuex的目录结构是

其中Tab代码如下:

import * as types from '../mutation-types';

const state ={
    showContent:[
        {subtitle:"北京",subCon:"首都……"},
        {subtitle:"上海",subCon:"金融……"},
        {subtitle:"广州",subCon:"吃货……"},
        {subtitle:"深圳",subCon:"小渔村……"}
    ],
    activeIndex:0,
};
const mutations = {
    [types.CHANGEACTIVE](state,index){
        console.log('log');
        console.log(state.activeIndex);
        state.activeIndex = index;
    },
    [types.CHANGECON](state,obj){
        state.showContent[obj.index].subCon = obj.con;
    }
}

export default {
    state,
    mutations
}

index.js代码如下:
import Vue from 'vue';
import Vuex from 'vuex';
import * as actions from './action';
import * as getters from './getter';
import Tab from './modules/Tab';
Vue.use(Vuex);

export default new Vuex.Store({

getters,
actions,
//项目中使用的方式
modules:{
    Tab
}
 // strict: true,

});
在对应的组件中使用如下代码

<script>
    import {mapGetters,mapState} from 'vuex';
    export default {
        data () {
            return {
                msg: 'Hello World!',
                // sindex: 0,
            }
        },
        computed:{
             ...mapGetters([
                 'getShowCon',
                ]),
            ...mapState(['activeIndex'])
        },
        methods:{
            clickTab(index){
                console.log(index);
                this.$store.commit('CHANGEACTIVE',index);
            }
        }

    }
</script>

actions代码如下:

import * as types from './mutation-types';

export const changeActive = ({commit,state},index)=>{
    console.log(1);
    commit(types.CHANGEACTIVE,index)
};

export const changeCon = ({commit,state},index,content)=>{
    commit(types.CHANGECON,{
        index:index,
        content:content,
    })
};

getters代码如下:

export const getShowCon = state => {
    console.log(state.Tab.showContent[state.Tab.activeIndex]);
  return state.Tab.showContent[state.Tab.activeIndex];
}

结果是获取不到activeIndex的值,一直是undefined,也获取不到getShowCon这个属性的值? 这是为什么?

解决方案

因為你有用到 modules,所以 activeIndex 的正確位置是在 store.state.Tab.activeIndex
而你用:

computed:{
    // 這是映射 store.state.activeIndex ,所以才 undefined
    ...mapState(['activeIndex']) 
},

改成

computed:{
    ...mapState({
        activeIndex: state => state.Tab.activeIndex
    }) 
},

應該就正確了。

这篇关于vue.js - vuex2.0中,mapState和mapGetters的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆