Reputation: 808
I want to dynamically import data from component file to router file and allow next()
depending upon value of imported data.
in App.vue I'm triggering this.$router.push({name: "Dashboard"})
when data authenticated: false
changes to true
. I'm triggering it with watch
.
Problem is, router file will always receive original value false
even with dynamic importing.
App.vue
watch: {
authenticated(){
console.log(this.authenticated) //Outputs 'true'
this.$router.push({name: 'Dashboard'}); //Triggers routing
}
}
router file (index.js)
{
path: '/dashboard',
name: 'Dashboard',
component: Dashboard,
beforeEnter(to, from, next){
(async ()=>{
const mod = await import('../view/App.vue'); //Dynamic import
let result = mod.default.data().auth; //Access 'authenticated' value from App.vue
console.log(result); //Output is 'false', but it should be 'true'
result ? next() : next({name: 'Login'});
})()
}
}
I tried many different async
methods as well but nothing worked.
Upvotes: 1
Views: 872
Reputation: 126
Use In-Component Guard
in your App.vue
as specified here and remove the authentication login from router
file:
beforeRouteLeave(to, from, next) {
if (to.name === 'Dashboard' && this.authenticated) {
next();
}
else {
next({ name: 'Login' });
}
}
Upvotes: 1