当前位置: 首页 > article >正文

Vue3中watchEffect、watchPostEffect、watchSyncEffect的区别

watchEffect 函数是不能获取到 DOM 更新后的值的

const x = ref(0)
const y = ref(0)
watchEffect(() => {
  y.value = x.value
  const xx = document.getElementById("x").value;
  console.log('watchEffect', y.value, xx)
})
const add = () => {
  for(let i=0;i < 5;i++) {
    x.value++
  }
}

x:<input type="text" v-model="x" id="x" disabled/><br />
y:<input type="text" v-model="y" id="y" disabled/>
<button @click.stop="add">add</button>

 

  callback(() => {
    const dom = document.getElementById("x").value;
    console.log('callback', dom)
  })

使用下面方式或是 watchPostEffect 是可以获取到DOM更新后的值

watchEffect(callback, {
  flush: 'post'
})
const x = ref(0)
const y = ref(0)
watchPostEffect(() => {
  y.value = x.value
  const xx = document.getElementById("x").value;
  console.log('watchEffect', y.value, xx)
})
const add = () => {
  for(let i=0;i < 5;i++) {
    x.value++
  }
}

x:<input type="text" v-model="x" id="x" disabled/><br />
y:<input type="text" v-model="y" id="y" disabled/>
<button @click.stop="add">add</button>

 

  callback(() => {
    const dom = document.getElementById("x").value;
    console.log('callback', dom)
  })

 

使用 watchSyncEffect 会同步触发更新,即监听值更新一次触发一次更新

const x = ref(0)
const y = ref(0)
watchSyncEffect(() => {
  y.value = x.value
  const xx = document.getElementById("x").value;
  console.log('watchEffect', y.value, xx)
})
const add = () => {
  for(let i=0;i < 5;i++) {
    x.value++
  }
}

x:<input type="text" v-model="x" id="x" disabled/><br />
y:<input type="text" v-model="y" id="y" disabled/>
<button @click.stop="add">add</button>

 

  callback(() => {
    const dom = document.getElementById("x").value;
    console.log('callback', dom)
  })


http://www.kler.cn/a/560990.html

相关文章:

  • 在LangFlow中集成OpenAI Compatible API类型的大语言模型
  • DeepSeek开源周高能开场:新一代高效推理引擎FlashMLA正式发布
  • EX_25/2/22
  • 115 道 MySQL 面试题,从简单到深入!
  • 《一起打怪兽吧》——自制一款Python小游戏
  • 基于Spring Boot的健康医院门诊在线挂号系统设与实现(LW+源码+讲解)
  • 超详细:数据库的基本架构
  • HandBrake for Mac v1.9.2 视频压缩及格式转换 汉化版 支持M、Intel芯片
  • TLS与自签名证书的创建、作用、用到的工具等知识的介绍
  • 反向代理模块kfj
  • 实操解决Navicat连接postgresql时出现‘datlastsysoid does not exist‘报错的问题
  • escape SQL中用法
  • 力扣-贪心-135 分发糖果
  • 如何加固织梦CMS安全,防webshell、防篡改、防劫持,提升DedeCMS漏洞防护能力
  • 将Ubuntu操作系统的安装源设置为阿里云
  • java23种设计模式-原型模式
  • 【网络编程】UDP协议
  • Spring Boot 项目中,JDK 动态代理和 CGLIB 动态代理的使用
  • 【无标题】PHP-get_definde_vars
  • Unity汽车笔记