Vue.js – two different components on same route

Loading...

Vue.js – two different components on same route

I’m trying to figure out how to have 2 different components on same route with Vue.
Main page or login page, depends if user is authenticated.
Maybe im missing something in documentation, but i cant and cant figure it out. Is it even possible?
Thx

Solutions/Answers:

Solution 1:

use auth param in router map:

router.map({
  '/home': {
    component: Home,
     auth: true
  },
  '/login': {
   component: Login
  },
  '/something': {
    component: Something,
    auth: true
  },
})

and then check before each transition:

router.beforeEach(function (transition) {
  if (transition.to.auth && !auth.user.authenticated) {
    transition.redirect('/login')
  } else {
    transition.next()
  }
})

Solution 2:

So you need dynamic components.

in whichever Vue is a parent to these components use a computed property that returns the name of component you want to use, based on the authenticated state:

//- in your js
//  insert into the vue instance definition, assuming you have an authencation 
//  property somewhere, eg session.isAuthenticated
... 
components: {
  MainComponent,
  LoginComponent
},
computed: {
  useComponent () {
    return session.isAuthenticated ? 'MainComponent' : 'LoginComponent'
  }
}
...

//- in your template html
<component :is='useComponent' />

http://vuejs.org/guide/components.html#Dynamic-Components

References

Loading...