Vue.js - two different components on same route

2019-05-08 06:23发布

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

2条回答
再贱就再见
2楼-- · 2019-05-08 07:02

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()
  }
})
查看更多
The star\"
3楼-- · 2019-05-08 07:16

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

查看更多
登录 后发表回答