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

相关推荐
国家不保护废物几秒前
Vue组件通信全攻略:从父子传到事件总线,玩转组件数据流!
前端·vue.js
写不来代码的草莓熊1 小时前
vue前端面试题——记录一次面试当中遇到的题(9)
前端·javascript·vue.js
JinSo1 小时前
pnpm monorepo 联调:告别 --global 参数
前端·github·代码规范
程序员码歌1 小时前
豆包Seedream4.0深度体验:p图美化与文生图创作
android·前端·后端
urhero1 小时前
工作事项管理小工具——HTML版
前端·html·实用工具·工作事项跟踪·任务跟踪小工具·本地小程序
二十雨辰1 小时前
eduAi-智能体创意平台
前端·vue.js
golang学习记1 小时前
从0死磕全栈之Next.js connection() 函数详解:强制动态渲染的正确姿势(附实战案例)
前端
郝学胜-神的一滴2 小时前
Three.js光照技术详解:为3D场景注入灵魂
开发语言·前端·javascript·3d·web3·webgl
m0dw2 小时前
vue懒加载
前端·javascript·vue.js·typescript
国家不保护废物2 小时前
手写 Vue Router,揭秘路由背后的魔法!🔮
前端·vue.js