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>

当子组件内同时修改 urloriurl 时,父组件中仅 purl 接收到了新值, poriurl 没变化

//coma 组件内
this.url = "new url";
this.oriurl = "new oriurl";

经排查, oriurlwatch 未触发,不中断点。

解决方法

  1. 改成延迟触发

    watch: {
        url (nval) {   
          this.$nextTick(()=>{
            this.$emit('update:url', nval)
          })
        },
        oriurl (nval) {
          this.$nextTick(()=>{
            this.$emit('update:oriurl', nval)
          })
        },
      },
    

    猜测是因为 urlwatch 内, emit 执行后,导致本次事件循环 event loop 跳过了其他 watch 方法

  2. 或者不使用 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

posted @ 2021-08-31 00:12  ShaynChow  阅读(538)  评论(0编辑  收藏  举报