# 路由獨享守衛
路由獨享守衛故名思議,就是當前的守衛只能給路由自己使用。如果說某個路由需要自己獨特的功能。比如當前頁面只能登錄成功才可以訪問,那么我們就要考慮如何攔截。
## 實現功能
在路由配置上直接定義`beforeEnter`守衛。這些守衛與全局前置守衛的方法參數是一樣的。
```
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
```
## 實現登錄攔截
實現的頁面中用戶登錄后才可以訪問。同樣的我們也可以做其它操作。比如購物車頁面,必須登錄后才可以訪問。
```
var login = true;
var router = new VueRouter({
routes: [
{path: '/home', components: {default: Home, tabbar: Tabbar}},
{path: '/cate', components: {default: Category, tabbar: Tabbar}},
{path: '/pingou', components: {default: Purchase, tabbar: Tabbar}},
{
path: '/cart',
components: {default: Cart, tabbar: Tabbar},
beforeEnter(to, from, next) {
if (login) {
next()
} else {
next('/home')
}
}
},
{path: '/user', components: {default: User, tabbar: Tabbar}},
{path: '/about', component: About},
{path: '*', component: Error404}
],
linkActiveClass: 'active',
linkExactActiveClass: 'exact-active'
});
export default router
```
## 有的同學會說為什么不在全局守衛添加這個功能?
加不加這個功能是由開發者決定的。我的想法是如果只有這個頁面需要登錄才可以訪問,那么我就不必大費周章在全局守衛,對所有路由一個一個做對比,再做攔截。我只需要對當前組件添加攔截,這樣簡單方便,性能還好。
當然了,如果有許多頁面都需要攔截,你可以對這些路由的`meta`項添加一個值。比如 `login:true` 如下圖。
```
var login = true;
var router = new VueRouter({
routes: [
{path:'/',redirect:'/home'},
{path: '/home', components: {default: Home, tabbar: Tabbar,}},
{path: '/cate', components: {default: Category, tabbar: Tabbar}},
{path: '/pingou', components: {default: Purchase, tabbar: Tabbar}},
{
path: '/cart',
components: {default: Cart, tabbar: Tabbar},
meta: {
login: true
}
},
{path: '/user', components: {default: User, tabbar: Tabbar}},
{path: '/about', component: About},
{path: '*', component: Error404}
],
linkActiveClass: 'active',
linkExactActiveClass: 'exact-active'
});
router.beforeEach((to, from, next) => {
console.log(to.meta)
if (to.meta.login) {
if(login){
next()
}else{
next('/')
}
} else {
next()
}
})
```