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}才可以开启深度监视

相关推荐
朝阳392 分钟前
react【实战】搜索框(含联动动画,清空按钮)
前端·javascript·react.js
gCode Teacher 格码致知3 分钟前
Javascript提高:一个彩色小球在画布边界内反弹并留下渐变轨迹-由Deepseek产生
开发语言·javascript
小王C语言10 分钟前
【linux进程信号】————产生信号:signal自定义信号处理动作(自定义捕捉)、前后台进程、产生信号的方式(函数、软条件、硬件异常)....等等
运维·服务器·前端
芝士就是力量啊 ೄ೨15 分钟前
Windows11使用Edge切屏后,会卡屏的解决方案
前端·edge
sinat_2554878117 分钟前
数组·学习笔记
java·javascript·笔记
尘世壹俗人31 分钟前
前端如何自适应宽高
前端
JianZhen✓39 分钟前
前端竞争力提升
前端
吃西瓜的年年42 分钟前
react(五)路由
前端·react.js·前端框架
IT_陈寒1 小时前
JavaScript的闭包差点让我加班到凌晨
前端·人工智能·后端
JianZhen✓1 小时前
前端面试攻略
前端