Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js router - conditional component rendering

Tags:

vue.js

 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.

like image 814
user3260392 Avatar asked Feb 20 '19 15:02

user3260392


People also ask

What is conditional rendering in Vue?

Conditional rendering refers to the ability to render distinct user interface (UI) markup based on whether a condition is true or not. This notion is frequently used in contexts like showing or hiding components (toggling), switching application functionality, handling authentication and authorization, and many more.

Does V-if destroy component?

v-if is "real" conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and re-created during toggles.

How do I create a dynamic route Vue?

Adding dynamic routes in VueUpdate the router/index. js file with the new route in the routes array. Remember to include the import for the Post component. Restart your app and head to localhost:8080/post/dynamic-routing in your browser.


1 Answers

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')
    }
  }  
}
like image 89
dari0h Avatar answered Oct 12 '22 14:10

dari0h