How to make an async call in a beforeCreate hook of a Vue instance?

你说的曾经没有我的故事 提交于 2019-12-19 15:36:12

问题


I am building a Vuejs app with authentication.

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.

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.

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

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
    })
  }

回答1:


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.



来源:https://stackoverflow.com/questions/40243417/how-to-make-an-async-call-in-a-beforecreate-hook-of-a-vue-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!