Vue3 watch的使用

html 复制代码
<template>
	<div class="ttt">
		<h2>{{age}}</h2>
		<button @click="addAge">年龄+1</button>
		<h2>{{age2}}</h2> 
		<button @click="updateReactive2">更新数据</button>
		<h2>{{refObj}}</h2>
		<h2>reactive3:{{reactive3}}</h2>
	</div>
</template>

<script setup lang="ts" name="testName">
	import {ref} from 'vue'
	import {reactive} from 'vue'
	import {toRefs} from 'vue'
	import {toRef} from 'vue'
	import {computed} from 'vue'
	import {watch} from 'vue'
	
	let refObj = ref([
		{id:1,name:'ref对象'},
		{id:2,name:'测试咯'}
	])
	
	function updateReactive2(){
		refObj.value = {id:3,name:'测试一下'}
		toRefId.value = 2 +1
		fullName.value = "啦啦啦啦啦"
	}
	
	//监视对象
	watch(refObj,(newValue,oldValue)=>{
		console.log("对象变化",newValue,oldValue)
	},{deep:true})//

	let age = ref(1)
	function addAge(){
		age.value = age.value + 1 
		age2 += 1
		refObj.value.name= 6666
	}
	
	//监视变量
	const swatch = watch(age,(newValue,oldValue)=>{
		console.log("数据值",newValue,oldValue)
		if(newValue>5){
			swatch()
		}
	})
	
	let reactive3 = reactive({id:1,name:'13123132测试数据'})
	//多属性监视
	const swatch2 = watch([()=>reactive3.id,()=>reactive3.name],(newValue,oldValue)=>{
		console.log("reactive对象多属性变化",newValue,oldValue)
	})
</script>

<style>
	.ttt{
		color:red
	}
</style>

以上代码,对变量和对象做了一个监听,deep

监视reactive会默认开启深度监视,ref需要指定{deep:true}才可以开启深度监视

相关推荐
泉城老铁6 分钟前
springboot+vue 如何实现海康摄像头喊话功能
前端·vue.js·后端
一 乐11 分钟前
美食推荐|基于springboot+vue的美食分享系统设计与实现(源码+数据库+文档)
前端·数据库·vue.js·spring boot·后端·美食
WX-bisheyuange13 分钟前
基于Spring Boot的电影院购票系统设计与实现
前端·javascript·vue.js·毕业设计
聊天QQ:6882388614 分钟前
基于Matlab与Simulink的滑模控制六自由度水下机器人运动模型:无缝轨迹跟踪,含S-f...
vue.js
qq_124987075323 分钟前
基于springboot+vue+mysql的校园博客系统(源码+论文+部署+安装)
java·vue.js·spring boot·mysql·毕业设计
通义灵码37 分钟前
用 Qoder 加速前端巨石应用的架构演进
前端·人工智能·架构·qoder
一水鉴天41 分钟前
整体设计 定稿 之21 拼语言表述体系之3 dashboard.html V5(codebuddy)
前端·人工智能·架构
前端fighter1 小时前
全栈项目:宠物用品购物系统及后台管理
前端·vue.js·后端
吃炒鸡蛋1 小时前
反射更新字段
java·服务器·前端
子洋1 小时前
LLM 原理 - 输入预处理
前端·人工智能·后端