flush选项表示回调函数调用的时机,有三个值可以选择
pre:默认值,表示在dom更新前调用,比如这是你需要再改变其他数据,就使用pre,这些数据改变完一起更新dom,提高性能
post:表示dom更新完成后调用,比如你要获取dom或者子组件,跟我们之前使用nextTick的意思一样
sync:同步调用
当flush 为 post
当你更改了响应式状态,它可能会同时触发 Vue 组件更新和侦听器回调。
默认情况下,用户创建的侦听器回调,都会在 Vue 组件更新之前被调用。这意味着你在侦听器回调中访问的 DOM 将是被 Vue 更新之前的状态。
如果想在侦听器回调中能访问被 Vue 更新之后的DOM,你需要指明 flush: 'post'
<script lang="ts" setup>
const num = ref(1);
const numRef = ref<HTMLElement | null>(null);
watch(num, (news) =>{
console.log(news)
// 当不加 {flush: 'post'} textContent等于 1
// 反之 textContent等于 2
console.log(numRef.value?.textContent, 'textContent')
},{flush: 'post'});
const onToggle = () =>{
num.value = 2;
}
</script>
<template>
<div ref="numRef" @click="onToggle">{{num}}</div>
</template>
网友评论