简体   繁体   English

Vue Router和VueJS的反应性

[英]Vue Router and VueJS reactivity

I've got this code for my vue-router : 我的vue-router有这个代码:

{ 
   path: '/templates/:id/items/:itemId', component: Item,
   name: 'item'
},

On the item object, I've got a computed property templateId : 在item对象上,我有一个计算属性templateId

templateId() {
   return parseInt(this.$route.params.id, 10);
},

The issue I have, is, each time I add an anchor to the url (clicking a link, INSIDE the item component), even if the component doesn't change, this property is computed again. 我有的问题是,每次我向网址添加一个锚点(点击链接,INSIDE item组件),即使组件没有改变,也会再次计算此属性。

It means that all computed properties depending of templateId will be computed again. 这意味着将再次计算取决于templateId所有计算属性。

But the templateId value doesn't change at all. 但templateId值根本不会改变。

Here is a really simple jsfiddle to explain the issue: 这是一个非常简单的解释问题的方法:

https://jsfiddle.net/1Lgfn9qh/1/ https://jsfiddle.net/1Lgfn9qh/1/

If I remove the watch property (never called), nothing is logged in the console anymore. 如果我删除了watch属性(从未调用过),则控制台中不再记录任何内容。

Can you explain me what's happening here? 你能解释一下这里发生了什么吗? Why the computed properties are recomputed, even if no values has been updated? 为什么重新计算计算属性,即使没有更新值? How can I avoid that? 我怎么能避免这种情况?

What's causing this behaviour is the fact, that the route object is immutable in Vue. 造成这种行为的原因是route对象在Vue中是不可变的。 Any successful navigation will result in a completely new route object therefore triggering a re-computation of all computed and watched properties. 任何成功的导航都将导致一个全新的路径对象,从而触发重新计算所有计算和监视的属性。 See https://router.vuejs.org/api/#the-route-object for more details. 有关详细信息,请参阅https://router.vuejs.org/api/#the-route-object

To solve this you can watch the route object and filter the relevant vs irrelevant changes for you there 要解决此问题,您可以watch路线对象并在那里过滤相关的vs无关的更改

watch: {
  '$route' (to, from) {
    if(to.path != from.path) { // <- you may need to change this according to your needs!
      this.relevantRoute = to
    }
  }
}

And then reference the manually set variable in your computed and/or watched properties 然后在计算和/或监视属性中引用手动设置变量

templateId() {
  return parseInt(this.relevantRoute.params.id, 10);
},

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

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