在Axios通话之外无法获得价值

Yor*_*len 0 javascript vue.js axios

我希望您能解决axios遇到的问题。

我只是想在通话之外获得价值,但无法发挥作用。这是一段小代码:

 axios.get('/api/get-user').then(({ data }) => {
            this.user = data;
            console.log(this.user); //returns the correct data
            return this.user;
        });

        console.log(this.user); //returns null
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?我也尝试过,let self = this但无济于事。我希望你们能帮助我!

Cal*_*ine 7

这是异步问题,您正在axios请求完成之前调用console.log。这就是为什么我们使用.then(res => {})的原因。

另一种选择是使用异步等待。

用异步装饰父函数

const myFunction = async() => {
    const {data} = await axios.get('/api/get-user');
    this.user = data;
    console.log(this.user);
}
Run Code Online (Sandbox Code Playgroud)

请参阅MDN以获取更多信息,此链接是示例(我认为对理解最有帮助)https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Examples