`async/await` 在 Vue.js `mounted` 中可用吗? [英] Is `async/await` available in Vue.js `mounted`?

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

问题描述

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

await fetchData1();等待 fetchData2UsingData1();doSomethingUsingData1And2();

所以我想知道这是否有效:

异步挂载() {等待 fetchData1();等待 fetchData2UsingData1();doSomethingUsingData1And2();},

在我的环境中,它没有引发任何错误,而且似乎运行良好.但是在这个问题中,生命周期钩子中的async/await没有实现.

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

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

解决方案

它会起作用,因为 mounted 钩子被调用 after 组件已经安装,换句话说它不会在渲染之前等待承诺解决.唯一的问题是,在 promise 解决之前,您将拥有一个空"组件.

如果您需要的是在数据准备好之前不渲染组件,则您需要在数据中添加一个标志,该标志与 v-if 一起工作,以便在一切就绪时渲染组件准备好了:

//在您的模板中<div v-if="dataReady">//你的html代码

//在你的脚本中数据 () {返回 {数据就绪:假,//其他数据}},异步挂载(){等待 fetchData1();等待 fetchData2UsingData1();doSomethingUsingData1And2();this.dataReady = true;},

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

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?

解决方案

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.

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

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

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