2017-08-15 434 views
3

我正在用Vue.js 2构建一个管理页面,我想阻止未经身份验证的用户访问/admin路由并将它们重定向到/login。对于我已经使用了In-组件卫队beforeRouteEnter在管理组件类似如下如何重定向到vue-router beforeRouteEnter挂钩内的其他url?

... 
beforeRouteEnter(to, from, next) { 
    if(userNotLogedIn) { 
    this.$router.push('/login'); 
    } 
} 

这里的问题是,thisbeforeRouteEnter挂钩定义。那么在这种情况下,访问$router并重定向到其他网址的正确方法是什么?

回答

2

documentation指出:

beforeRouteEnter后卫没有获得this,因为确认导航前 后卫被调用,因此新 进入组件甚至还没有尚未创建。

您可以通过调用next这样重定向到另一页:

beforeRouteEnter(to, from, next) { 
    if(userNotLogedIn) { 
    next('/login'); 
    } 
} 

这里是另一种方式来实现相同的结果:所以不是每个受保护的航线上使用beforeRouteEnter,你可以定义受保护的途径在使用meta财产路由器的配置,然后使用上的所有路线beforeEach钩和检查保护路线并在需要时重定向到登录页面:

let router = new Router({  
    mode: 'history',  
    routes: [  
    { 
     path: '/profile', 
     name: 'Profile', 
     component: Profile, 
     meta: { 
     auth: true // A protected route 
     }, 
    },  
    { 
     path: '/login', 
     name: 'Login', 
     component: Login, // Unprotected route 
    }, 
    ] 
}) 

/* Use this hook on all the routes that need to be protected 
instead of beforeRouteEnter on each one explicitly */ 

router.beforeEach((to, from, next) => {  
    if (to.meta.auth && userNotLoggedIn) { 
    next('/login') 
    }  
    else { 
    next() 
    }  
}) 

// Your Vue instance 
new Vue({ 
    el: '#app', 
    router, 
    // ... 
}) 
+0

谢谢@Ikbel ..这解决了这个问题 –