Vuex getter返回未定义

时间:2018-11-30 13:37:15

标签: javascript vue.js vuejs2 vue-component vuex

这是我的store.js代码:

export const store = new Vuex.Store({
    state: {
        staffID: '',
        count: 0,
    },
    getters:{
        getStaffID: state => {
            console.log("13 getStaffID: " + state.staffID)
            return state.staffID;
        }
    },
    mutations: {
        UPDATE_STAFFID: (state,value) => {
            state.staffID = value
            console.log("20 mutations: " + state.staffID)
        },
    },
    actions: {
        update_staffID: (context, payload) => {
            context.commit("UPDATE_STAFFID", payload)
        }
    }
  })

在我的组件中,有一个按钮将称为:

this.$store.commit('UPDATE_STAFFID','miow')
console.log("store.getStaffID: " + this.$store.getStaffID);
console.log("store.staffID: " + this.$store.staffID);

结果日志将显示以下内容:

20 mutations: miow
13 getStaffID: miow
store.getStaffID: undefined
store.staffID: undefined

这对我来说很困惑。从日志中,我可以得出结论:

  • 变异UPDATE_STAFFID运行正常
  • store.js中的getStaffID getter中的
  • state.staffID将输出期望的值miow
  • 但上述getter的返回值将以某种方式返回undefined
  • 尝试使用this.$store.staffID直接访问staffID值也将返回undefined

为什么选择那些undefined

1 个答案:

答案 0 :(得分:4)

您缺少gettersstate属性,因此请像这样添加它们:

 console.log("store.getStaffID: " + this.$store.getters.getStaffID);
 console.log("store.staffID: " + this.$store.state.staffID);