Home > Net >  Vue - check localStorage before initial route (for token)
Vue - check localStorage before initial route (for token)

Time:10-26

I have a Vue app which does a little localStorage and server check on app load, to determine where to initially route the user.

This is in the App's main entry component, in the created() hook

My problem is that the default / route's Component visibly loads first, then the server call and everything happens which causes the user the route to their correct location

How can I delay the rendering of the initial component until my app's main component created() method completes, and then purposely navigates the user to the correct route?

CodePudding user response:

EDIT: I just saw you used the created method... like mentioned below use beforeRouteEnter instead with the next() parameter it provides

First of all I wouldn't recommend using a delay but instead a variable that keeps track if the API call is done or not. You can achieve this using the mounted method:

data() {
  return {
    loaded: false,
  }
}
async mounted() {
  await yourAPICALL()
  if (checkIfTokenIsOkay) {
    return this.loaded = true;
  }
  // do something here when token is false
}

Now in your html only show it when loaded it true:

<div v-if="loaded">
  // html
</div>

An better approuch is using the beforeRouteEnter method which allows you to not even load the page instead of not showing it: enter image description here

enter image description here

  • Related