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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM