Vue.js已挂载`async/await`吗? [英] Is `async/await` available in Vue.js `mounted`?

查看:258
本文介绍了Vue.js已挂载`async/await`吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在mounted() {}中做这样的事情:

I'd like to do something like this in mounted() {}:

await fetchData1();
await fetchData2UsingData1();
doSomethingUsingData1And2();

所以我想知道这是否可行:

So I wonder if this works:

async mounted() {
    await fetchData1();
    await fetchData2UsingData1();
    doSomethingUsingData1And2();
},

在我的环境中,它不会引起任何错误,并且似乎运行良好. 但是在此问题中,未实现生命周期挂钩中的async/await.

In my environment it raises no errors, and seems to work well. But in this issue, async/await in lifecycle hooks is not implemented.

https://github.com/vuejs/vue/issues/7209

我找不到更多信息,但实际上可用吗?

I could not find further information, but is it available in fact?

推荐答案

它将起作用,因为mounted挂钩在组件已安装后被称为 ,换句话说,它不会等待渲染前要解决的承诺.唯一的事情是,在诺言解决之前,您将拥有一个空"组件.

It will work because the mounted hook gets called after the component was already mounted, in other words it won't wait for the promises to solve before rendering. The only thing is that you will have an "empty" component until the promises solve.

如果您需要的是在数据准备就绪之前不呈现组件,则您需要在数据中带有一个标志,该标志与v-if一起使用以在一切准备就绪时呈现组件:

If what you need is the component to not be rendered until data is ready, you'll need a flag in your data that works along with a v-if to render the component when everything is ready:

// in your template
<div v-if="dataReady">
    // your html code
</div>


// inside your script 
data () {
    return {
        dataReady: false,
        // other data
    }
},

async mounted() {
    await fetchData1();
    await fetchData2UsingData1();
    doSomethingUsingData1And2();
    this.dataReady = true;
},

这篇关于Vue.js已挂载`async/await`吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆