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
})
},
應該就正確了。
以上是 vuex2.0中,mapState和mapGetters的使用 的全部内容, 来源链接: utcz.com/a/149983.html