我有一个Vue-App,可与Vuex和Axios一起运行。在这个应用程序中,我有vuex-store来处理API调用,但是问题是,当我调用store-actions时,我无法在调用者中链接响应。任何想法我在做什么错了吗?
呼叫代码:
import { FETCH_PRODUCTS, ADD_PRODUCT } from './actions.type'
methods: {
sendNewProduct () {
this.$store
.dispatch(ADD_PRODUCT, this.newProductForm)
.then(() => {
console.log('This never gets called')
})
}
}
Vuex商店:
const actions = {
[ADD_PRODUCT] (context, credentials) {
return new Promise((resolve) => {
ApiService
.post('/Products/', {
Name: credentials.Name,
Description: credentials.Description,
Price: credentials.Price
})
.then(({ data }) => {
this.$store
.dispatch(FETCH_PRODUCTS)
resolve(data)
})
.catch(({ response }) => {
console.log(response)
context.commit(SET_ERROR, 'Error adding product')
})
})
}
}
答案 0 :(得分:1)
const actions = {
[ADD_PRODUCT](context, credentials) {
return ApiService.post("/Products/", {
Name: credentials.Name,
Description: credentials.Description,
Price: credentials.Price
})
.then(({ data }) => {
this.$store.dispatch(FETCH_PRODUCTS);
return data;
})
.catch(({ response }) => {
console.log(response);
context.commit(SET_ERROR, "Error adding product");
throw new Error("Error adding product");
});
}
};
我删除了new Promise(...)
,因为axios已经创建了一个promise。
如果在return data
回调中添加了then
,并在catch
回调中抛出了异常,以使调用api接收数据/错误。
请注意,承诺会在FETCH_PRODUCTS完成之前解决,为确保操作也已完成,请输入:
.then(({ data }) => {
return this.$store.dispatch(FETCH_PRODUCTS)
.then(() => data);
})