watchEffect

<template>
  <div>
    <input type="text" v-model="name" />
    <div id="beWatch"></div>
    <!-- <button @click="stopEffect">停止</button> -->
  </div>
  </template>
 
  <script setup lang='ts'>
  import { ref, watchEffect } from 'vue'
 
  let name = ref('')
  // 写法不同,不需要指定监听某个数据
  // 非惰性,函数内不需要数据变动也会执行一次,相当于watch的immediate: true
  // watchEffect(() => {
  //   console.log(name.value, 'watchEffect')
  // })
 
  // 接受一个oninvalidate回调函数,在oninvalidate函数内写的函数会在监听的数据变动时优先执行,但是不会在第一次执行
  // watchEffect((oninvalidate) => {
  //   oninvalidate(() => {
  //     console.log('before')
  //   })
  //   console.log(name.value, 'watchEffect')
  // })
  // 'bofore' 'watchEffect'
 
  // watchEffect返回一个函数,调用这个函数可以停止监听
  // const stop = watchEffect(() => {
  //   console.log(name.value, 'watchEffect')
  // })
  // const stopEffect = () => {
  //   stop()
  // }
 
  watchEffect(() => {
    const div = document.getElementById('beWatch')
    // 不设置flush时候打印出来是null,设置fulsh为post能够打印出来该元素
    console.log("%c Line:38 🥟 div", "color:#33a5ff", div);
  }, { flush: 'post' }) // flush: 'sync' 表示同步执行, pre表示在dom更新前执行, post表示在dom更新后执行
  </script>
 
  <style scoped lang='scss'>
 
  </style>

posted on   ChoZ  阅读(3)  评论(0编辑  收藏  举报

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示