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)
})