beforeRouteUpdate 和观看“$route"之间的区别 - Vue.js? [英] Difference between beforeRouteUpdate and watching '$route' - Vue.js?

查看:27
本文介绍了beforeRouteUpdate 和观看“$route"之间的区别 - Vue.js?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,要对同一组件中的参数更改做出反应,我们使用 beforeRouteUpdate 钩子或观看 $route.

As we know, to react to params changes in the same component we use beforeRouteUpdate hook or watching $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 路由器引入了 beforeRouteUpdate?

What is the difference between these two? if both are same then why vue router introduced beforeRouteUpdate?

推荐答案

来自 beforeRouteUpdate 上的文档:

From the documentation on beforeRouteUpdate:

当渲染此组件的路由发生变化时调用,但此组件在新路由中被重用.例如,对于带有动态参数 /foo/:id 的路由,当我们在 /foo/1/foo/2 之间导航时,相同的 Foo 组件实例将被重用,并且在发生这种情况时将调用此钩子.

called when the route that renders this component has changed, but this component is reused in the new route. For example, for a route with dynamic params /foo/:id, when we navigate between /foo/1 and /foo/2, the same Foo component instance will be reused, and this hook will be called when that happens.

不可否认,文档不清楚在 $route 对象的值实际改变之前,钩子被调用.这就是这个导航钩子和在 $route 上设置观察者的区别,它会在 $route 的值改变后被调用.

The documentation is admittedly unclear that the hook gets called before the value of the $route object actually changes. That's the difference between this navigation hook and setting a watcher on $route, which will get called after the value of $route has changed.

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

Using the beforeRouteUpdate navigation guard, you can determine whether or not you want to prevent the route from changing (by not calling next()) or go to a different route entirely (by passing a different route value like next('/foo'), next({ name: 'foo' }), etc.).

这是一个示例 fiddle,显示了这些函数何时被调用.

Here's an example fiddle that shows when these functions get called.

这篇关于beforeRouteUpdate 和观看“$route"之间的区别 - Vue.js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆