12.v3+ts的watch

本文详细介绍了Vue中watch函数的用法,包括浅层监听、深层监听以及针对特定属性的监听。同时,还讲解了watchEffect的使用场景,包括自执行和参数传递以清除副作用。
摘要由CSDN通过智能技术生成
watch
<template>
  <div class="container">
    case1: <input type="text" v-model="message">
    <hr>
    case2: <input type="text" v-model="notice.foo.bar.name">
    <hr>
    watchEffect:<input type="text" v-model="effects">
  </div>
</template>

<script setup lang='ts'>
import { reactive, ref, watch, watchEffect } from 'vue'

let message = ref<string>('起飞')
let notice = ref({
  foo:{
    bar:{
      name:"起飞2"
    }
  }
})

// 监听多个用数组[xx,xx] 浅层次
watch(message,(newVal,oldVal) => {
  console.log('新'+ newVal,'旧'+ oldVal)
})

// 多层次的话 需要开启深度监听
// 如果多层次用了reactive,他是默认开启深度监听
// watch(notice,(newVal,oldVal) => {
//   console.log('新'+ newVal,'旧'+ oldVal)
// },{
//   deep:true
// })

// 如果要监听属性特定的值,需要使用函数的形式
watch(() => notice.value.foo.bar.name,(newVal,oldVal) => {
  console.log('新'+ newVal,'旧'+ oldVal)
},{
  deep:true,
  // immediate:true // 立刻执行
})

let effects = ref<string>('哈哈哈')

// 启动自执行
// watchEffect(() => {
//   console.log('effects',effects);
//   console.log('message',message);
// })

// 可接收参数,清除负作用
watchEffect((oninvalidate) => {
  // 在监听之前执行一次
  oninvalidate(()=>{
    console.log(2);
  })
  console.log('effects',effects.value);
})


</script>

<style lang="scss" scoped>

</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值