Vue 中 watch 的一个坑
开发所用 Vue 版本 2.6.11
子组件 coma 中两个属性:
props: {
url: {
type: String,
default: ''
},
oriurl:{
type: String,
default: ''
}
}
再增加两个 watch 监听这两个属性,如有变化通知父组件:
watch: {
url (nval) {
this.$emit('update:url', nval)
},
oriurl (nval) {
this.$emit('update:oriurl', nval)
},
},
父组件内使用 sync 监听属性变化:
<coma :url.sync="purl" :oriurl.sync="poriurl"></coma>
当子组件内同时修改 url 和 oriurl 时,父组件中仅 purl 接收到了新值, poriurl 没变化
//coma 组件内
this.url = "new url";
this.oriurl = "new oriurl";
经排查, oriurl 的 watch 未触发,不中断点。
解决方法
-
改成延迟触发
watch: { url (nval) { this.$nextTick(()=>{ this.$emit('update:url', nval) }) }, oriurl (nval) { this.$nextTick(()=>{ this.$emit('update:oriurl', nval) }) }, },猜测是因为
url的watch内,emit执行后,导致本次事件循环event loop跳过了其他watch方法 -
或者不使用
watch,在修改后马上执行 $emit//coma 组件内 this.url = "new url"; this.oriurl = "new oriurl"; this.$emit('update:url', nval) this.$emit('update:oriurl', nval)
tag
vue watch emit 不执行 两个 多个
本文地址:https://zhouxc.notion.site/Vue-watch-64f7942e40f54d8f8b59fe144dc4e2f8
浙公网安备 33010602011771号