[英]Vuex Action - Returning Axios Promise
我在兩個地方使用 axios 返回的承諾時遇到了一些困難。 我想在我的 Vuex 操作中使用 .then .then()
來提交對我的狀態的更改,返回 axios 承諾並在我的組件中再次使用 .then .then()
來更新 UI。 我遇到的問題是我的組件內未定義承諾響應。
// 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 .then()
的使用,則response
將成為我的 api 中的對象,但我希望在我的組件中有一個承諾,以便我可以catch
錯誤。
// component
methods: {
getUser(userId) {
this.$store.dispatch('GET_USER', userId)
.then(response => {
console.log(response); // no longer undefined
});
}
}
// vuex
actions: {
GET_USER: ({commit}, userId) => {
return api.getUserById(userId); // removed 'then' method
}
}
第一個代碼塊有什么問題?
謝謝。
在第一個塊中,您then
不返回任何內容:因此它返回undefined
。 返回已解決的值應該可以解決此問題。
你必須搜索、mapGetter、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..
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.