源码
Demo.vue
<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',
//Vue2的写法
/*watch:{
//简写:
//sum(newValue,oldValue){
// console.log('sum的值变化了,newValue,oldValue=',newValue,oldValue)
//}
//完整版写法: 写为一个对象
//这样写的优势:可以配置一些属性
sum:{
//配置一些属性:
immediate:true, //表示立即监听
deep: true, //深度监视
//监视的回调
handler(newValue,oldValue){
console.log('sum的值变化了,newValue,oldValue=',newValue,oldValue)
}
}
},*/
setup(){
//数据
let sum = ref(0)
let msg = ref('你好啊')
//Vue3 写法:可以多次调用 watch() 函数
//情况一:监视 ref() 所定义的 一个 响应式数据
/* watch(sum,(newValue,oldValue)=>{
console.log('sum变了',newValue,oldValue)
},{immediate:true})
//继续增加 watch ^_^
watch(msg,(newValue,oldValue)=>{
console.log('msg变了',newValue,oldValue)
},{immediate:true})
*/
//上面的2个可以合并为下面的一个,利用数组
//情况二:监视 ref() 所定义的 多个 响应式数据
/*watch([sum,msg],(newValue,oldValue)=>{
console.log('sum或msg变了',newValue,oldValue)
},{immediate:true}) */
//返回一个对象(常用)
return {
sum,
msg
}
}
}
</script>
