vuex无法获取getters属性this.$store.getters.getCurChildId undefined

问题描述

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']
    }
  },

参考阅读

https://blog.csdn.net/yanguo110/article/details/80997507

猜你喜欢

转载自www.cnblogs.com/fozero/p/11107850.html
今日推荐