user3260392
user3260392

Reputation: 171

Vue.js router - conditional component rendering

 routes: [
{
  path: '/',
  name: 'home',
  get component(){
    if(Vue.loggedIn){
      return Home
    }else{
      return Login
    }
  }  
}

I've added a getter and seems to work fine but any variable or function i use in the if statement is undefined. even i've tried using global prototype.$var and mixin functions still with no success.

All i need is if a user is logged in the path '/' renders Dashboard view and if not then Login is rendered to '/'.

Note: I've used beforeEnter: and it works fine. but i don't want redirection.

Upvotes: 8

Views: 9481

Answers (2)

TJ Weems
TJ Weems

Reputation: 1114

In my application I use a router.beforeEach to check if user has logged in. I used a getter to check if logged in state is correct. I also used meta to only show views depending on if user has logged in or not.

I applied this code to the entry point of the application main.js

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!store.getters.loggedIn) {
      next({
        path: '/login',
      })
    } else {
      next()
    }
  } else if (to.matched.some(record => record.meta.requiresVisitor)) {
    // this route is only available to a visitor which means they should not be logged in
    // if logged in, redirect to home page.
    if (store.getters.loggedIn) {
      next({
        path: '/',
      })
    } else {
      next()
    }
  }
})

In my router.js file I have the meta set as this

routes: [
  {
    // this is the route for logging in to the app
    path:      '/login',
    name:      'login',
    component: () => import(/* webpackChunkName: "login" */ './views/Login.vue'),
    props:     true,
    meta:      {
      requiresVisitor: true,
      layout:          'landing',
    },
  },
  {
    // this is the dashboard view
    path:      '/',
    name:      'dashboard',
    component: () => import(/* webpackChunkName: "dashboard" */ './views/Dashboard.vue'),
    meta:      {
      requiresAuth: true,
      layout:       'default',
      breadCrumb:   [
        { name: 'Dashboard' }
      ]
    }
  },
]

notice the meta object. if you are using vue devtools you will see that these params are available to use for validation.

Upvotes: 1

dari0h
dari0h

Reputation: 897

Using your approach this is what I found is working:

routes: [
{
  path: '/',
  name: 'home',
  component: function () {
    if(loggedIn){
      return import('../views/Home.vue')
    }else{
      return import('../views/Login.vue')
    }
  }  
}

Upvotes: 6

Related Questions