ajax - How to make the delay when a user check on Vue.js? -


i have spa application on vue.js + laravel. authorization logic, delegated laravel app. however, need check auth status, when routing has changed. create small class, responsible it.

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

within component has method called when change url.

beforerouteenter (to, from, next) { next(vm =>{   auth.check(vm);     if (!auth.user.authenticated) {       next({path:'/login'});     } }) } 

function next() given vue app instance, check user object. if user false, next() call again redirect login page. works, when page loaded. if i'll reload /account page, there redirect /login page, because request api not completed yet, code continue execute. idea?

quite simple do, need make code work asynchronously , hold routing before request 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 loading indicator when loading application doesn't seem freeze (you can use global router hooks that)
  • if using vue-resource, consider using interceptors (perhaps in addition routing checks)
  • consider using router.beforeeach don't have copy-paste beforerouteenter every component

Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -