源码
Demo.vue
<template>
<h2>当前求和为:{{sum}}</h2>
<button @click="sum++">点我+1</button>
<hr>
<h2>当前的信息为:{{msg}}</h2>
<button @click="msg+='!'">修改信息</button>
<hr>
<!-- 演示情况3 -->
<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('你好啊')
//ref() 会生成一个 RefImpl 实例对象。
let person = ref({ //如果此处写成 ref({}) 来定义 对象,实际上在ref()里面还是调用的 reactive()
name:'张三',
age:18,
job:{
j1:{
salary:20
}
}
})
//输出为 RefImpl 实例对象,简称为 Ref对象
console.log(sum) // sum.value ∈ 基本类型的值
console.log(msg) // msg.value ∈ 基本类型的值
console.log(person) //person.value ∈ Proxy(求助reactive,变为了 reactive 生成的一个代理对象)
//ref() 需要使用.value
//错误写法:
//watch(sum.value,(newValue,oldValue)=>{ //报错 不能监测值,而是应该监测保存数据的结构
//正确写法:
watch(sum,(newValue,oldValue)=>{ //实测有效果
console.log('sum的值变化了', newValue, oldValue)
})
//此写法,只能监测 person 这个 RefImpl实例对象的地址发生了变化才会触发。 如果只是修改其中属性的值,不会触发。
//原因: person 是由 ref() 生成的
//watch(person,(newValue,oldValue)=>{
//如果想监测 RefImpl实例对象 中某个属性值 是否发生了变化,需要使用 .value(实际借助了 reactive() 生成的 Proxy数据)
//reactive() 定义的Proxy数据 特点: 自动开启深度监视。
/*watch(person.value, (newValue,oldValue)=>{
console.log('person的值变化了', newValue, oldValue)
})*/
//第2种方法: 给 ref() 生成的 refImpl实例对象 开启深度监测。
watch(person, (newValue,oldValue)=>{
console.log('person的值变化了', newValue, oldValue)
},{deep:true})
//返回一个对象(常用)
return {
sum,
msg,
person
}
}
}
</script>
