无法在我的组件中使用操作返回的值



我的store操作返回一个值,我希望在从组件调用该操作时检查该值。但是由于某种原因,我得到的只是undefined,而不是我实际从任何操作返回的任何值。

为什么?

存储行动:

export const actions = {
async initialize ({ state, commit, dispatch }) {
await this.$axios.get('myEndpoint')
.then((res) => {
return true
}).catch((error) => {
return false
})
}
}

组件代码:

async mounted () {
const initializeResult = await this.initialize()
console.log(initializeResult)
}

您必须尊重vuex存储模式,首先您应该创建一个可以在突变中进行突变的状态,该突变也可以在您的操作中的异步回调中提交:

export const state={
initResult:null
}
export const mutations={
SET_RESULT(state,payload){
state.initResult=payload
}
}
export const actions = {
async initialize ({ state, commit, dispatch }) {
await this.$axios.get('myEndpoint')
.then((res) => {
commit('SET_RESULT',true)
}).catch((error) => {
commit('SET_RESULT',false)
})
}
}

,然后在你的组件中调度挂载的钩子内的动作,并使用计算属性返回状态:

computed:{
result(){
return this.$store.initResult;
}
},
mounted () {
this.$store.dispatch('initialize')

}

最新更新