created() 生命周期钩子中的 vue 异步调用 [英] vue async call in created() lifecycle hook

查看:248
本文介绍了created() 生命周期钩子中的 vue 异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 created() 中调用以下方法.为此,我需要将 created() 设为 async.根据 Vue 文档,created()同步调用.Vue 框架会在 created()await 以避免任何竞争条件吗?

I need to call below method in created(). For this purpose, I need to make created() as async. Per Vue documentation, created() is called synchronously. Will Vue Framework await on created() to avoid any race conditions?

this.isAuthenticated = await authService.isAuthenticated();

推荐答案

Vue.config.productionTip = false;

function tm(ms, msg) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(msg);
    }, ms);
  });
}

new Vue({
  async beforeCreate() {
    console.log(await tm(1000, "BEFORE CREATE"));
  },
  async created() {
    console.log(await tm(2000, "CREATED"));
  },
  async beforeMount() {
    console.log(await tm(3000, "BEFORE MOUNT"));
  },
  async mounted() {
    console.log(await tm(4000, "MOUNTED"));
  }
}).$mount("#app");

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

这篇关于created() 生命周期钩子中的 vue 异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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