也许是一个愚蠢的问题但是,当我从'outside'函数调用api时,它总是返回undefined,例如:
actions.js
import axios from 'axios'
export function getProducts() {
axios.get('http://localhost:8000/api/products').then((response) => {
return response;
});
}
然后在一个组件中:
mounted() {
this.products = getProducts();
console.log(this.products);
}
返回undefined
当然,当我从组件发出请求时,它返回结果
mounted() {
axios.get('http://localhost:8000/api/products').then((response) => {
this.products = response;
console.log(this.products);
});
}
为什么会发生这种情况?如何解决这个问题?
谢谢
你在response
电话的then
回调中返回axios.get
值。但是,你的getProducts
函数不会返回任何内容。
只需返回axios.get
电话:
export function getProducts() {
return axios.get('http://localhost:8000/api/products');
}
然后,getProducts
的结果将是由Promise
返回的axios.get()
。所以,你可以在then
的结果上添加一个getProducts
回调,并为你设置this.products
:
mounted() {
getProducts().then(products => this.products = products);
}