Search code examples
javascriptvue.jsvuejs2vue-routervue-cli

Is there a way to load different views for one route depending on user role?


Is there some implementation if I want to use the main page path '/' for different views depending on roles? Like if you are an authorized user you will see the MainAuth, if you are a guest you will see the MainGuest? Here is some code that would help me to explain.

const routes = [
  {
    path: '/',
    name: 'main_auth',
    component: MainAuth,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/',
    name: 'main_guest',
    component: MainGuest,
    meta: {
      requiresGuest: true
    }
  }
]

For this example, it just loads the first path I declared whatever I am a guest or user. To be more specific, I have a login/register module on the main path '/' and I want to load an authorized user page on the same path '/' after login.


Solution

  • Since you want to use only one path, you could use a basic route and do the work in the component itself. The route:

    const routes = [
      {
        path: '/',
        name: 'main',
        component: Main,
      }
    ]
    

    Main view component:

    <template>
      <div>
        <Auth v-if="!loggedIn" />
        <MainContent v-else />
      </div>
    </template>
    

    Auth component:

    <template>
      <div>
        <Login v-if="showLogin" />
        <Register v-else />
      </div>
    </template>
    

    With this, you check if the user is logged in from the Main view component and show either the Auth component or the main content.

    Then, in the Auth component, you use a toggle that allows the user to switch between a Login and Register component.