Vuex行动-返回Axios的承诺

时间:2018-12-06 10:30:03

标签: javascript vue.js vuex

我在两个地方使用axios返回的诺言时遇到了一些困难。我想在Vuex动作中使用.then()来提交对状态的更改,返回axios承诺,并在组件内部再次使用.then()来更新UI。我遇到的问题是在组件内部未定义promise响应。

// component
methods: {
  getUser(userId) {
    this.$store.dispatch('GET_USER', userId)
      .then(response => {
        console.log(response); // undefined
      });
  }
}

// vuex
actions: {
  GET_USER: ({commit}, userId) => {
    return api.getUserById(userId)
      .then(({data}) => {
        commit('ADD_USER', data);
      });
  }
}

// api service
getUserById(userId) {
  return axios.get('/api/users/' + userId);
}

如果我在Vuex动作中取消使用.then(),则response会成为我api的对象,但我希望在组件中有个承诺,以便我可以{{1 }}错误。

catch

第一个代码块有什么问题?
谢谢。

2 个答案:

答案 0 :(得分:1)

在第一段中,您的then不返回任何内容:因此它返回undefined。返回解析的值应该可以解决此问题。

答案 1 :(得分:0)

您必须搜索,mapGetters,mapActions,并且必须检查异步功能

例如

如果您请求使用api,则可以执行此操作。

//api.js

import axios from 'axios'
export aync function getuser() {
  ... 
  ...
  const data = await axios.get(url,{params:{....}})
  return data
}
//component
import {getuser} from '@/app.js'
import {mapAction} from 'vuex'
  data() {
  return {
    data:null
  }
}
methods: {
..mapAction('getUserAction')
  async getUserMethod () {
    this.data = await getuser()
    this.getUserAction(this.data)
  }
}



//store.js
actions: {

getUserAction () {
  // your actions..
  }
}