1

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.

1
  • You're accessing auth not authenticated. Commented Aug 19, 2020 at 23:20

1 Answer 1

1

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' });
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

This answer is based on the scope of question you've asked. The authentication logic can get very diverse depending on the project structure. I'd suggest to store the authenticated variable in vuex so that every component that requires authentication can access that variable
Thank you for answering. I declared beforeRouteEnter(from, to, next) in App.vue but it's not triggering. App.vue is where <router-link> for Dashboard is located. Am I doing this right?
Just store the authenticated variable in vuex because you might use this variable somewhere else too to protect different routes. Then you can use authenticated variable in beforeEnter as you have mentioned in your question like this: store.state.authenticated. See this
I didn't learn Vuex yet but I guess I'll have to hang on to this issue until I learn it. Thank you for answering.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.