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-pastebeforeRouteEnter
to every component
- [Vuejs]-Vues.js unit test mutations: cannot complete testing of function
- [Vuejs]-VueJS replace data of component // same route problem
Source:stackexchange.com