Vic*_*ico 5 javascript vue.js vue-router vuejs2
我有这个代码vue-router:
{
path: '/templates/:id/items/:itemId', component: Item,
name: 'item'
},
Run Code Online (Sandbox Code Playgroud)
在 item 对象上,我有一个计算属性templateId:
templateId() {
return parseInt(this.$route.params.id, 10);
},
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,每次我向 url 添加锚点(单击链接,在item组件内部)时,即使组件没有更改,也会再次计算此属性。
这意味着templateId将再次计算所有依赖于的计算属性。
但是 templateId 值根本没有改变。
这是一个非常简单的jsfiddle来解释这个问题:
https://jsfiddle.net/1Lgfn9qh/1/
如果我删除 watch 属性(从未调用过),控制台中将不再记录任何内容。
你能解释一下这里发生了什么吗?即使没有更新任何值,为什么要重新计算计算属性?我怎样才能避免这种情况?
导致这种行为的原因是该route对象在 Vue 中是不可变的。任何成功的导航都会产生一个全新的路线对象,从而触发所有计算和监视属性的重新计算。请参阅https://router.vuejs.org/api/#the-route-object了解更多详细信息。
为了解决这个问题,您可以watch在路由对象中过滤相关与不相关的更改
watch: {
'$route' (to, from) {
if(to.path != from.path) { // <- you may need to change this according to your needs!
this.relevantRoute = to
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在计算和/或监视的属性中引用手动设置的变量
templateId() {
return parseInt(this.relevantRoute.params.id, 10);
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
353 次 |
| 最近记录: |