问题
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