我正在用Vue建立一个管理页面.JS2和我想阻止未经验证的用户访问/admin路径,并将他们重定向到/login.为此,我在管理组件中使用了组件Guard beforeRouteEnter,如下所示

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

这里的问题是beforeRouteEnter hook中没有定义this.那么,在这种情况下,访问$router并重定向到其他url的正确方式是什么?

推荐答案

documentation条规定:

beforeRouteEnter守卫无法进入this,因为

您可以通过如下方式调用next重定向到另一个页面:

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

下面是实现相同结果的另一种方法:因此,您可以使用meta属性在路由配置中定义受保护的路由,而不是在每个受保护的路由上使用beforeRouteEnter,然后在所有路由上使用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,
  // ...
})

Vue.js相关问答推荐

Vue路由路径匹配行为

Vue3组合-如何在组件卸载时注销回调

更新 Shopware 管理 CMS 组件中的编辑器视图

v-model 修饰符返回空

将 v-calendar 与以时间和日期格式出现的事件一起使用

手动触发对观察到的对象/数组的更新

将初始值设置为可直接在 HTML 中使用的 vue.js 模型

webpack vue-loader 配置

如何在vue中动态加载组件

Vuetify v-data-table ,如何在 HTML 中呈现标题文本?

在 Vuejs 中Watch观察 window.scrollY 的变化

为什么Vue.js 使用单字标签

错误:您可能需要额外的加载器来处理这些加载器的结果.

请求正在进行时显示加载器

Vue Cli 3 不允许我在 Webpack 中处理 SVG

我可以使用react路由创建别名路由吗?

使用props向组件添加类名

无法访问函数内的数据属性

Vuejs获取事件正在调用的元素?

VueJS 按键查找元素