watch

<template>
  <div>
    <input type="text" v-model="name" />
    <input type="text" v-model="obj.age" />
    <input type="text" v-model="refName.age" />
  </div>
  </template>
 
  <script setup lang='ts'>
  import { ref, reactive, watch } from 'vue'
 
  let name = ref('')
  let refName = ref({
    age: 18
  })
  let obj = reactive({
    age: 18
  })
 
  // watch必须监听的是响应式数据
 
  // 基础用法
  // watch(name, (newVal, oldVal) => {
  //   console.log(newVal, oldVal)
  // }, { immediate: true }) // immediate: true 表示立即执行一次
 
  // 监听对象中的某个属性需要使用函数,不可以写成watch(obj.age, (newVal, oldVal) => {})
  // watch(() => obj.age, (newVal, oldVal) => {
  //   console.log(newVal, oldVal)
  // })
 
  // 监听多个数据需要使用数组
  // watch([name, () => obj.age], ([newName, newAge], [oldName, oldAge]) => { // 对应的也是数组
  //   console.log(newName, oldName, newAge, oldAge)
  // })
 
  // deep属性在监听reactive默认开启,监听ref对象需要手动开启
  // watch(refName, (newVal, oldVal) => {
  //   console.log(newVal, oldVal)
  // }, { deep: true })
  // 换成指向到某个属性则不需要开启deep
  // watch(() => refName.value.age, (newVal, oldVal) => {
  //   console.log(newVal, oldVal)
  // })
 
  // 新增属性flush不常用,在watcheffect中会用到
  watch(name, (newVal, oldVal) => {
    console.log(newVal, oldVal)
  }, { flush: 'sync' }) // flush: 'sync' 表示同步执行, pre表示在dom更新前执行, post表示在dom更新后执行
  </script>
 
  <style scoped lang='scss'>
 
  </style>

posted on   ChoZ  阅读(8)  评论(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
点击右上角即可分享
微信分享提示