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

相关推荐
YHL4 分钟前
🎯 Danci —— 用 AI 驱动开发一个全栈英语单词学习平台
前端·后端
平头哥~5 分钟前
Day 20 _ 3D 翻卡_perspective 写错人,卡片就穿帮
前端·3d·css3·学习资料
小聪70813 分钟前
elpis-core 前端 Webpack 工程化实践
前端
2601_9539880714 分钟前
Ricon组态实时监控 - 毫秒级数据可视化
前端·物联网·数学建模·信息可视化·架构·前端框架
mONESY15 分钟前
让大模型「听话」输出 JSON:LangChain OutputParser 结构化输出实战,从手写正则到 Zod Schema 四层进化
javascript
V1588972620138 分钟前
从滴滴模式看机器人租赁:撮合型租赁平台开发源码的调度系统设计思路
linux·前端·机器人
研☆香1 小时前
js中使用的正则表达式
开发语言·javascript·正则表达式
szarron1 小时前
国产手持式频谱分析仪选型攻略:TFN RC系列 vs HTOOL SA8T频谱分析仪 专业参数对比(军工/路测/调试全覆盖)
开发语言·前端·状态模式
BS30813_vx1 小时前
31754+基于 Spring Boot + Vue 的网络文学交流分享平台设计与实现
vue.js·spring boot·后端
开开心心就好1 小时前
免费桌签打印工具,支持批量导入名字
前端·javascript·人工智能·docker·jupyter·智能手机·语音识别