Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuejs component created wait for data to load first

I have an App.vue component where I want to load the currently logged in user. I also want to redirect the user when he\she tries to go the login route and the currently logged in user is already saved in context (he's already signed in).

// inside App.vue component
created() {
  AuthService.getCurrentUser().then((user) => {
    this.user = user;
  });
}

I have a check in the created method of the login component for whether the currentUser is setted, but then when the user tries to go to the login page it might be possible that the the request for the current user is not finished.

My question is:

How do I wait for the data to load before the App.vue component loads? I saw something like this:

waitForData: true,
data(transition) {
  return AuthService.getCurrentUser().then(currentUser => {
    transition.next({ currentUser });
  });
}

which doesn't actually wait for the data to be loaded and the component loads anyway.

Edit: I'm aware of beforeRouteEnter but this is App.vue component which is a parent component of all components and not a route specific component.

like image 900
Nikola Avatar asked Oct 23 '17 13:10

Nikola


2 Answers

I ran into a very similar problem and solved by adding a v-if on the element that wrapped the child component that depends on the loaded data. And then of course have an data property to control that v-if. If you don't have a wrapping element you can always use a template element to do the wrapping.

like image 197
Robert Aarts Avatar answered Nov 12 '22 02:11

Robert Aarts


This is not the Vue way of doing things.

  1. Use VUEX to store your currentUser object
  2. Set up the Vuex getters in App.vue's computed section. Your template will be updated dynamically once the data is ready.

See the mapGetters section in this page. It works very well with the computed mechanism.

You can also use v-if in your relevant component, so that the component won't be created before your data is ready in VUEX.

like image 10
Jason Ching Avatar answered Nov 12 '22 03:11

Jason Ching