Vue.js已挂载`async/await`吗?

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;
},