0
The way to check if the current route requires authentication is documented here: https://router.vuejs.org/en/advanced/meta.html
Change your beforeEach
method to this:
router.beforeEach((to,from,next) => {
if(to.matched.some(record => record.meta.requiresAuth)){
// do something
}
next();
}
0
As mentioned in the Documentation,
All route records matched by a route are exposed on the
$route
object (and also route objects in navigation guards) as the
$route
.matched Array. Therefore, we will need to iterate over
$route.matched
to check for meta fields in route records.
router.beforeEach((to,from,next) => {
if(to.matched.some(record => record.meta.requiresAuth)){
authUser = '';
const authUser = JSON.parse(window.localStorage.getItem('authUser'))
if(authUser && authUser.access_token){
next()
}else{
next({
path: '/login',
query: { redirect: to.fullPath }
})
}
}
next()
})
- [Vuejs]-VueJS data initialization for non existent objects
- [Vuejs]-How to download a file from json api backend using vue?
0
I just switched the position of router.beforeEach
to be before
const app = new Vue({
el: '#app',
router,
});
So, in full, the code looks like this:
import router from './routes.js';
require('./bootstrap');
router.beforeEach((to,from,next) => {
if(to.matched.some(record => record.meta.requiresAuth)){
const authUser = JSON.parse(window.localStorage.getItem('authUser'))
if(authUser && authUser.access_token){
next()
}else{
next({
path: '/login',
query: { redirect: to.fullPath }
})
}
}
next()
})
const app = new Vue({
el: '#app',
router,
});
- [Vuejs]-Vue conditional rendering
- [Vuejs]-Vue.js – Computed property is not triggered when data is changing
Source:stackexchange.com