[Vuejs]-How to make the delay when a user check on Vue.js?

0👍

Done. Need to return promise like that

check: function(context) {
 return context.$http.get('/api/v1/user').then((response) => {
  if (response.body.user != null) {
   this.user.authenticated = true
  }
}, (response) =>{
    console.log(response)
   });
}

and then

beforeRouteEnter (to, from, next) {
   Auth.check().then(()=>{
      if(!Auth.user.authenticated) 
        next({path:'/login'})
      else
        next();
   })
}

0👍

Quite simple to do, you need to make your code work asynchronously and hold routing before request is completed.

export default {
    user: {
        authenticated : false
    },
    check: function(context) {
        return context.$http.get('/api/v1/user').then((response) => {
            if (response.body.user != null) {
                this.user.authenticated = true
            }
        }, (response) => {
            console.log(response)
        });
    }
}

then

beforeRouteEnter (to, from, next) {
    next(vm => {
        Auth.check(vm).then(() => {
            if (!Auth.user.authenticated) {
                next({path:'/login'});
            } else {
                next()
            }
        }
    })
}

Other pro tips

  • Display some loading indicator when loading so your application doesn’t seem to freeze (you can use global router hooks for that)
  • If you are using vue-resource, consider using interceptors (perhaps in addition to the routing checks)
  • Consider using router.beforeEach so that you don’t have to copy-paste beforeRouteEnter to every component

Leave a comment