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

相关推荐
2501_946230985 小时前
Cordova&OpenHarmony通知中心实现
android·javascript
南山安5 小时前
JavaScript 函数柯里化:从入门到实战,一文搞定(面试可用)
javascript·面试·函数式编程
谢尔登5 小时前
Monorepo 架构
前端·arcgis·架构
啃火龙果的兔子6 小时前
JavaScript 中的 Symbol 特性详解
开发语言·javascript·ecmascript
栀秋6666 小时前
你会先找行还是直接拍平?两种二分策略你Pick哪个?
前端·javascript·算法
漂流瓶jz6 小时前
PostCSS完全指南:功能/配置/插件/SourceMap/AST/插件开发/自定义语法
前端·javascript·css
xhxxx6 小时前
传统工具调用太痛苦?LangChain 一键打通 LLM 与真实世界
前端·langchain·llm
南山安6 小时前
LangChain学习:Memory实战——让你的大模型记住你
前端·javascript·langchain
武昌库里写JAVA6 小时前
iview-CRUD模板
vue.js·spring boot·sql·layui·课程设计
BD_Marathon7 小时前
Promise基础语法
开发语言·前端·javascript