如何在 Vue 实例的 beforeCreate 钩子中进行异步调用? [英] How to make an async call in a beforeCreate hook of a Vue instance?

查看:247
本文介绍了如何在 Vue 实例的 beforeCreate 钩子中进行异步调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个带有身份验证的 Vuejs 应用.

I am building a Vuejs app with authentication.

当页面加载并初始化app Vuejs 实例时,我使用beforeCreate 钩子来设置用户对象.我从 localStorage 加载 JWT 并将其发送到后端进行验证.

When the page is loaded and I initialise the app Vuejs instance, I am using beforeCreate hook to set up the user object. I load a JWT from localStorage and send it to the backend for verification.

问题在于这是一个异步调用,并且在调用返回结果之前,这个 app 对象的组件(导航栏、视图等)正在使用空的用户数据进行初始化验证.

The issue is that this is an async call, and the components of this app object (the navbar, the views etc.) are being initialised with the empty user data before the call returns the result of the verification.

在 promise 对象解析之前延迟子组件的初始化的最佳做法是什么?

What is the best practice to delay the initialisation of child components until a promise object resolves?

这是我的 Vue 应用程序对象中的内容:

Here is what I have in my Vue app object:

beforeCreate: function(){
    // If token or name is not set, unset user client
    var userToken = localStorage.userToken;
    var userName = localStorage.userName;
    if (userToken == undefined || userName == undefined) {
      StoreInstance.commit('unsetUserClient');
      // I WANT TO RESOLVE HERE
      return;
    }

    // If token and name is set, verify token
    // This one makes an HTTP request
    StoreInstance.dispatch({type: 'verifyToken', token: userToken}).then((response) => {
      // I WANT TO RESOLVE HERE
    }, (fail) => {
      // I WANT TO RESOLVE HERE
    })
  }

推荐答案

当前的生命周期回调是没有任何承诺/异步行为的函数.不幸的是,似乎没有办法在您加载数据时使应用程序暂停".相反,您可能希望在 beforeCreate 函数中开始加载并设置一个标志,显示一个带有空数据的加载屏幕/骨架,在数据加载时翻转标志,然后渲染适当的组件.

The current lifecycle callbacks are functions without any promises/async behaviour. Unfortunately, there does not appear to be a way to cause the app to "pause" while you load data. Instead, you might want to start the load in the beforeCreate function and set a flag, display a loading screen/skeleton with empty data, flip the flag when the data has loaded, and then render the appropriate component.

这篇关于如何在 Vue 实例的 beforeCreate 钩子中进行异步调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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