繁体   English   中英

Vue 路由器 beforeEnter 与 beforeEach

[英]Vue Router beforeEnter vs beforeEach

我正在尝试将未登录用户从所有页面重定向到/login 我试过beforeEach()但当用户使用直接 url (如/home/event )进入站点时它不会触发。

Per-Route Guard beforeEnter()完美地工作,因为一旦用户登陆该特定页面,它就会触发。 但是,它需要我在每条路线上添加beforeEnter()

我正在寻找一种在路由器上几乎每个页面(甚至在动态页面上)上复制beforeEnter()的方法,非登录用户将被重定向到/login

当用户直接输入 url /home时,此选项有效。

routes: [
  {
    path: '/home',
    name: 'home',
    beforeEnter(to, from, next){
      if ( to.name !== 'login' && !this.isloggedin ){
         next({
           path: 'login',
           replace: true
         })
      } else {
         next()
      }
    }
  },
  ...
]

这仅在用户进入站点并更改路线后才有效

vm.$router.beforeEach((to, from, next)=>{
  if ( to.name !== 'login' && !this.isloggedin ){
    next({
      path: 'login',
      replace: true
    })
  } else {
    next();
  }
})

提前致谢。

看起来beforeEach是在一个初始化的组件中定义的,这意味着第一个路由已经发生。 使用您的路由在路由器模块中定义它:

const router = new VueRouter({
...
})

router.beforeEach((to, from, next)=>{
  if ( to.name !== 'login' && !this.isloggedin ){
    next({
      path: 'login',
      replace: true
    })
  } else {
    next();
  }
})

希望您使用的是 Vuex 并且可以为store.state.isloggedin导入商店。 如果还没有使用 Vuex,这说明了为什么它对全局 state 很有用。

对于全局且简洁的解决方案,您可以使用router.beforeResolve(async (to, from, next) => {});控制App.vue中的路由器行为 .

beforeResolvebeforeEach好,因为beforeResolve不会加载访问路径 URL 的组件,除非您手动触发下一个function。

这非常有用,因为除非您检查用户的身份验证状态然后调用next() ,否则您不会呈现任何界面。

例子:

   router.beforeResolve(async (to, from, next) => {
  // Check if the user is authenticated.
  let isUserAuthenticated = await apiRequestCustomFunction();

  // Redirect user to the login page if not authenticated.
  if (!isUserAuthenticated) {
    location.replace("https://example.com/signin");
    return false;
  }
  
  // When next() is called, the router will load the component corresponding
  // to the URL path.
  next();
});

提示:您可以在检查用户是否通过身份验证时显示加载器,然后执行操作(重定向到登录页面或正常加载应用程序)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM