Home > database >  Vue Router - Same path, different components
Vue Router - Same path, different components

Time:03-22

In Vue Router I want to show different components in the same path, based on a variable.

If isFirstTimeAccess is true i want to show Welcome Component, if it is false I want to show AuthHandler component in the same path on the browser -> /my-sub-url/

Example:

export const router = createRouter({
    history: createWebHistory(),
    routes: [{
            path: '/my-sub-url/',
            component: welcome,
            beforeEnter(to, from, next) {
                if (store.getters.isFirstTimeAccess) {
                    next();
                } else {
                    next({
                        name: 'auth'
                    });
                }
            },
            children: [{
                    name: 'auth',
                    path: '',
                    component: AuthHandler,
                },
            ]
        }
    ];
});

but If i tried this code if I set :

  • isFirstTimeAccess === true -> it works and show the welcome component

  • isFirstTimeAccess === false -> it show me this error in browser:

[Vue Router warn]: Detected an infinite redirection in a navigation guard when going from "/" to "/my-sub-url/". Aborting to avoid a Stack Overflow. This will break in production if not fixed. vue-router.esm-bundler.js:72

[Vue Router warn]: Unexpected error when starting the router: Error: Infinite redirect in navigation guard

Can someone help me please?

CodePudding user response:

Try this way

<template>
  <component :is="checkComponentAccess"></component>
</template>

<script>

export default {
  components: {
    WelcomeComponent: () => import("/path/to/component/WelcomeComponent"),
    SecondTimeComponent: () => import("/path/to/component/SecondTimeComponent")
  },
  computed: {
    ...mapGetters("user", ["isFirstTimeAccess"]),
    checkComponentAccess() {
      return this.isFirstTimeAccess === "citizen" ? "FirstComponent" : "SecondComponent";
    }
  }
};
</script>

CodePudding user response:

This seems to be a perfect case for Vue Router's navigation guards. They even have a specific example for an authentication case like yours.

Just copied from there:

router.beforeEach(async (to, from) => {
  if (
    // make sure the user is authenticated
    !isAuthenticated &&
    // ❗️ Avoid an infinite redirect
    to.name !== 'Login'
  ) {
    // redirect the user to the login page
    return { name: 'Login' }
  }
})
  • Related