api请求返回undefined

问题描述 投票:1回答:1

也许是一个愚蠢的问题但是,当我从'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);
        });
    }

为什么会发生这种情况?如何解决这个问题?

谢谢

rest vue.js axios
1个回答
1
投票

你在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);
}
© www.soinside.com 2019 - 2024. All rights reserved.