简体   繁体   中英

Differentiate between route change and page refresh in vue navigation guard?

I am working on a project where I need to push the user to sign in page if he is not authenticated, and my router guard is working fine. however I don't want this code to run if the user refreshed the page or came directly to the link. I want this because I want it to wait for user auto sign in which takes a few hundred milliseconds for firebase auth. But I do not want to wait every time the route changes only when the page is refreshed because firebase re-signs in the user only on page refresh not every router push. this is what I want to acheive in theory

Routes.forEach((to, from, next)=> {
if(!isSignedIn && to.name != 'signInPage' && pageNotRefreshed) {
next('/sign-in')
}
else if (pageRefreshed && !isSignedIn && to.name != 'signInPage' ) {
// Wait 500ms and then run the upper condition one more time because firebase returns
// currentUser as empty as soon as page refreshes and takes some time to sign in and
// return isSignedIn  as true

}
}) 

Thanks

I think the best way to solve your problem will be creating in App.vue watch block which will wait till value will change and then redirect user. I don't know where you store isSignedIn variable but I suppose in Vuex.

//get value from store
computed: {
  isLoggedIn() {
    return this.$store.getters.isSignedIn
  }
},
watch: {
  //listen for changes of value
  isLoggedIn(newValue) {
    //if user is not authorized yet redirect to login panel
    if (!newValue && this.$route.name !== 'sign-in') {
      this.$router.push('/sign-in')
    }
  }
}

With this solution you avoid hard coded waiting time (some people can have much bigger latency so 500ms will be too low value).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM