为什么使用beforeRouteEnter而不是mounted?

lap*_*tou 4 vue.js vue-router

为什么beforeRouteEntervue-router 中存在导航守卫?是否存在beforeRouteEnter会被解雇但mounted不会被解雇的情况?如果不是,在什么情况下您更愿意使用beforeRouteEnterto mounted

Gio*_*ane 5

mounted是任何 Vue 组件的生命周期钩子,它总是会被触发。beforeRouteEnter或由其添加的任何其他生命周期挂钩的想法vue-router是允许您控制您的应用程序。

例如,假设您有一个名为的路由,bar该路由具有非常特定的验证逻辑,仅允许用户在前一个路由为 的情况下输入该逻辑foo,您可以将该验证逻辑插入此挂钩中,而不是检查该钩子中的每个路由更改。全球守卫。

export default {
  name: 'Bar',
  beforeRouteEnter(to, from, next) {
    if (from.name === 'foo') {
      next(); // Calling next allow the route to proceed
    } else {
      next(false); // Don't allow the navigation
      // or
      next({
        name: 'foo',
        query: {
          from: 'bar'
        }
      }); // Redirect to any desired route as navigation made in $router
    }
  }
}
Run Code Online (Sandbox Code Playgroud)