首页 > 解决方案 > 无法在我的组件中使用操作返回的值

问题描述

我的商店操作返回一个值,当从我的组件调用该操作时,我想检查该值。但由于某种原因,我得到的只是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)
}

标签: vue.jsvue-componentvuex

解决方案


您必须尊重 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')
 
}

推荐阅读