我正在使用Vue.js 2构建管理页面,我想阻止未经身份验证的用户访问/ admin路由并将其重定向到/ login.为此我在Admin组件中使用了之前的组件保护,如下所示
- ...
- beforeRouteEnter(to,from,next) {
- if(userNotLogedIn) {
- this.$router.push('/login');
- }
- }
这里的问题是在beforeRouteEnter钩子中没有定义.那么在这种情况下访问$router并重定向到不同URL的正确方法是什么?
解决方法
documentation指出:
The
beforeRouteEnter
guard does NOT have access tothis
,because the
guard is called before the navigation is confirmed,thus the new
entering component has not even been created yet.
- beforeRouteEnter(to,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,next) => {
- if (to.Meta.auth && userNotLoggedIn) {
- next('/login')
- }
- else {
- next()
- }
- })
- // Your Vue instance
- new Vue({
- el: '#app',router,// ...
- })