Vue93 vue3 watch监视ref属性的说明

html 复制代码
<template>
	<h2>当前求和为:{{sum}}</h2>
	<button @click="sum++">点我+1</button>
	<hr>
	<h2>当前的信息为:{{msg}}</h2>
	<button @click="msg+='!'">修改信息</button>
	<hr>
	<h2>姓名:{{person.name}}</h2>
	<h2>年龄:{{person.age}}</h2>
	<h2>薪资:{{person.job.j1.salary}}K</h2>
	<button @click="person.name+='~'">修改姓名</button>
	<button @click="person.age++">增长年龄</button>
	<button @click="person.job.j1.salary++">涨薪</button>
</template>

<script>
	import {ref,reactive,watch} from 'vue'
	export default {
		name: 'Demo',
		setup(){
			//数据
			let sum = ref(0)
			let msg = ref('你好啊')
			let person = ref({
				name:'张三',
				age:18,
				job:{
					j1:{
						salary:20
					}
				}
			})

			console.log(person)

			watch(sum,(newValue,oldValue)=>{
				console.log('sum的值变化了',newValue,oldValue)
			})

			watch(person,(newValue,oldValue)=>{
				console.log('person的值变化了',newValue,oldValue)
			},{deep:true})


			//返回一个对象(常用)
			return {
				sum,
				msg,
				person
			}
		}
	}
</script>

监视person时,不加.value是监视person对象。加了.value是监视person内部通过reactive生成的对象。

相关推荐
2分钟速写快排7 小时前
孔乙己的茴字有多少种写法?|AI 对话实时通信的三种实现
前端·javascript·github
Penge6669 小时前
JavaScript:BOM 详解
前端
梯度下降者9 小时前
Nuxt框架
vue.js·服务端渲染·全栈开发·混合渲染·nuxt框架
Penge6669 小时前
Vite vs Webpack:前端构建工具原理与实战
前端
Penge66610 小时前
前端包管理工具:npm、Yarn、pnpm 快速入门
前端
Penge66610 小时前
Sass 了解
前端
Penge66610 小时前
Webpack 打包从 0 到 1 实战笔记
前端
Penge66610 小时前
Webpack 入门:是什么、为什么需要、怎么使用?
前端
Penge66611 小时前
Ant Design(Antd)了解
前端
wangruofeng11 小时前
同一行代码,百种渲染:Asuka、React Native 与 Flutter 跨平台渲染机制深度拆解
前端·github