問題描述
this.$store.getters.getCurChildId undefined
這是因為我們設置了命名空間namespaced: true,
在vuex官網中對命名空間的描述如下:
默認情況下,模塊內部的 action、mutation 和 getter 是注冊在全局命名空間的——這樣使得多個模塊能夠對同一 mutation 或 action 作出響應。
如果希望你的模塊具有更高的封裝度和復用性,你可以通過添加 namespaced: true 的方式使其成為帶命名空間的模塊。當模塊被注冊后,它的所有 getter、action 及 mutation 都會自動根據模塊注冊的路徑調整命名。
import * as types from '../mutation-types.js'
const state = {
curChildId: '',
}
// getters
const getters = {
getCurChildId(state){
return state.curChildId
}
}
// actions
const actions = {
setCurChildId({ commit }, childId){
commit(types.SET_CURRENT_CHILDID, childId)
}
}
// mutations
const mutations = {
[types.SET_CURRENT_CHILDID](state, childId) {
state.curChildId = childId
}
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
問題解決
所以,調用的時候我們需要加上路徑,如:
this.$store.dispatch('childs/setCurChildId', item.id)
this.$store.getters['childs/getCurChildId']
computed: {
getCurChildId2 () {
return this.$store.getters['childs/getCurChildId']
}
},