<script setup>
import { ref, watch, onMounted } from 'vue'
import './index.css'
const count = ref(0)
const handleCount = () => {
count.value++
}
watch(count, (newValue, oldValue) => {
console.log(newValue, oldValue)
})
//即时回调的侦听器
watch(
count,
(newValue, oldValue) => {
console.log(newValue, oldValue)
},
{ immediate: true }
)
//一次性侦听器
watch(
count,
(newValue, oldValue) => {
console.log(newValue, oldValue)
},
{ once: true }
)
//Post Watchers
//如果想在侦听器回调中能访问被 Vue 更新之后的所属组件的 DOM,你需要指明 flush: 'post' 选项:
watch(
count,
(newValue, oldValue) => {
console.log(newValue, oldValue)
},
{
flush: 'post',
}
)
onMounted(() => {
console.log(1)
})
</script>
<template>
<div class="m-home-wrap">
home
<button @click="handleCount">{{ count }}</button>
<div class="m-home-demo"></div>
</div>
</template>
<style></style>
参考链接
https://cn.vuejs.org/guide/essentials/watchers.html