vue3 watch的用法

简介: vue3 watch的用法

1.监听普通类型

const index = ref(0);
watch(index,(newValue,oldValue)=>{
  console.log("新值是"+newValue, "旧址是"+oldValue);
})

2.监听多个普通类型

const index = ref(0);
const inends = ref(0)
watch([index,inends],(newValue,oldValue)=>{
  console.log("新值是"+newValue, "旧址是"+oldValue); //返回的是一个数组
})

3.监听响应对象

const person = reactive({
   name:"柳小刀",
   age:18,
   sex:"男"
})
watch(person,(newValue,oldValue)=>{
  console.log(newValue,oldValue);
})

此时 oldValue 失效,并且强制开启了不会生效的deep,返回一个proxy对象,要想使oldValue有效需要监听响应对象的某个属性

4.监听对象的某个属性 , 第一个参数应该传入一个函数表达式

const person = reactive({
   name:"柳小刀",
   age:18,
   sex:"男"
})
watch(()=>person.name,(newValue,oldValue)=>{
  console.log(newValue,oldValue);
})

5.监听reative对象嵌套对象 此时deep是生效的

const person = reactive({
   name:"柳小刀",
   age:18,
   sex:"男",
   hobbe:{
     sing:"唱歌",
     dangce:"跳舞"
   }
})
watch(()=>person.hobbe,(newValue,oldValue)=>{
  console.log(newValue,oldValue);
})

此时oldValue有效 ,说明vue3默认是开启深度监听了


相关文章
|
3天前
|
JavaScript 前端开发 CDN
vue3速览
vue3速览
12 0
|
3天前
|
设计模式 JavaScript 前端开发
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
|
3天前
|
JavaScript API
Vue3 官方文档速通(中)
Vue3 官方文档速通(中)
18 0
|
3天前
|
缓存 JavaScript 前端开发
Vue3 官方文档速通(上)
Vue3 官方文档速通(上)
20 0
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
8 1
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
7 0
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
6 0
|
6月前
|
缓存 JavaScript
vue中computed和watch的区别
vue中computed和watch的区别
|
5天前
|
缓存 JavaScript
|
10月前
|
缓存 JavaScript
Vue 中 computed 和 watch 的区别
Vue 中 computed 和 watch 的区别
55 0