首页 > 其他 > 详细

Vue 中 watch 的一个坑

时间:2021-09-02 06:09:56      阅读:10      评论:0      收藏:0      [点我收藏+]

开发所用 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)
          })
        },
      },
    

    猜测是因为 watch 内直接 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

Vue 中 watch 的一个坑

原文:https://www.cnblogs.com/ohzxc/p/15208478.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!