vue.js - beforeRouteUpdate 和 watching '$route' - Vue.js 之间的区别?

标签 vue.js vuejs2 vue-router

正如我们所知,为了对同一组件中的参数更改使用react,我们使用 beforeRouteUpdate Hook 或观察 $route

正在观看 $route:

const User = {
  template: '...',
  watch: {
    '$route' (to, from) {
      // react to route changes...
    }
  }
}

beforeRouteUpdate 方法:

const User = {
  template: '...',
  beforeRouteUpdate (to, from, next) {
    // react to route changes...
    next()
  }
}

这两者有什么区别?如果两者相同那么为什么 vue router 引入了 beforeRouteUpdate

最佳答案

来自documentationbeforeRouteUpdate 上:

called when the route that renders this component has changed, but this component is reused in the new route. For example, given a route with params /users/:id, when we navigate between /users/1 and /users/2, the same UserDetails component instance will be reused, and this hook will be called when that happens. Because the component is mounted while this happens, the navigation guard has access to this component instance.

诚然,文档并不清楚钩子(Hook)是在 $route 对象的值实际改变之前被调用的。这就是此导航 Hook 与在 $route 上设置观察者之间的区别,$route 的值发生更改后将被调用。

使用 beforeRouteUpdate 导航守卫,您可以确定是否要阻止路由更改(通过不调用 next())或转到不同的路径完全路由(通过传递不同的路由值,如 next('/foo')next({ name: 'foo' }) 等)。

这是一个例子 fiddle显示这些函数何时被调用。

关于vue.js - beforeRouteUpdate 和 watching '$route' - Vue.js 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47184331/

相关文章:

vuejs2 - 带有日期选择器输入的 V 模型

javascript - Vue 子路由

templates - 对.vue扩展名感到困惑- “Unknown custom element: <topmenu>”

vue.js - Vue JS 路由器查询传递并绑定(bind)到 axios

javascript - Vue.js 预填充数据

html - Vue.js "@click.prevent"is hiding the HTML "required"attribute default validation message(Please fill the field.)

vue.js - 如何将状态从 vuex store 共享到所有子组件

vue.js - 子事件发生后立即通知父组件?

vue.js - 如何将 vuetify 2.0 beta 安装到新的 vue cli 项目中?

css - Vue2 v-if 使我的转换不起作用