vuejs从入门到精通—— Vue3技术_watch时的value问题

83 阅读1分钟

解答一下在用watch时产生的疑惑!当用watch监视,用ref定义的数据的时候 到底点不点value?

template 代码:

<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>

js代码:

export default {
name :' Demo',
setup()(
//数据    ref定义基本数据类型
let sum = ref(0)
let msg = ref('你好啊')
let person = reactive({
name:'张三',
age:18,
job:{
    j1:{
    salary:20
    }
  }
})
//ref定义基本数据类型 因为 sum里存的基本数据类型的值
watch(sum,(newValue,oldValue)=>{
    console.log('sum的值变化了',newValue,oldValue)
})
//错误写法:  加.value  则会报错 功能实现不了
watch(sum.value,(newValue,oldValue)=>{
    console.log('sum的值变化了',newValue,oldValue)
})
//ref定义的对象  本质是 借助reactive函数生成的value
方法一:
watch(person.value,(newValue,oldValue)=>{
    console.log('person的值变化了',newValue,oldValue)
})
方法二:
watch(person,(newValue,oldValue)=>{
    console.log('person的值变化了',newValue,oldValue)
},{deep:true})
//返回一个对象(常用)
return{
    sum,
    msg,
    person
}

那为什么这么写呢?其实proxy是借助了 reactive 函数生成的:

微信图片_20230809160919.png