setup(){
let name=ref('张三')
let a=ref(0)
let b=ref(1)
let person=reactive({
firstName:'李',
lastName:'四',
sex:'男',
job:{
city:{
salary:'10000'
}
}
})
一、computed计算属性新特性
1.简写,不考虑计算属性被修改的情况
let fullName=computed(()=>{
return person.firstName+'-'+person.lastName
})
2.详细,给计算属性配getter和setter
let fullName=computed(
get(){
return person.firstName+'-'+person.lastName
}
set(value){
const newValue=value.split('')
person.firstName=newValue[0]
person.lastName=newValue[1]
}
)
二、watch监听属性新特性
watch(value,callback,options)值,值改变所触发的回调函数,配置项(immediate,deep默认为true,设置fasle无效)
1、watch监听单个ref对象
watch(name,(newValue,oldValue)=>{
console.log('newValue......',newValue)
console.log('oldValue......',oldValue)
console.log(name发生改变了)
})
2、watch监听多个ref对象
watch([name,a,b],(newValue,oldValue)=>{
console.log('newValue......',newValue)
console.log('oldValue......',oldValue)
//输出两者都是数组形式
console.log(name或a或b发生改变了)
})
3、watch监视reactive数据中的所有数据
当改变person中的属性时
watch(person,(newValue,oldValue)=>{
console.log('newValue......',newValue)
console.log('oldValue......',oldValue)
console.log(person发生改变了)
})
此时会报出person发生了变化,但是新值和旧值一样
4、watch监听reactive数据中的某个属性
watch(person.firstName,(newValue,oldValue)=>{
console.log('newValue......',newValue)
console.log('oldValue......',oldValue)
console.log(person发生改变了)
})
切记不能这么写,person.name是个死数据,watch监听的是ref,reactive,数组,函数等类型数据
所以我们需要将其写成函数形式,此时新值和旧值不一样,正常输出
watch(()=>person.firstName,(newValue,oldValue)=>{
console.log('newValue......',newValue)
console.log('oldValue......',oldValue)
console.log(person发生改变了)
})
5、watch监听reactive数据中的多个属性
watch([()=>person.firstName,()=>{person.lastName}],(newValue,oldValue)=>{
console.log('newValue......',newValue)
console.log('oldValue......',oldValue)
console.log(person发生改变了)
})
6、特殊情况
watch(()=>person.job,(newValue,oldValue)=>{
console.log('newValue......',newValue)
console.log('oldValue......',oldValue)
console.log(person发生改变了)
})
此时当改变job里面的salary时watch检测不到,需要在配置项中开启深度监视,但此时新值和旧值依旧一样
7、总结
watch监听基本类型的数据时,新值和旧值正常有效
但是监听对象类型时新值和旧值一样(无效)
当watch监听reactive对象时默认开启深度监视,但监视reactive对象的的某个属性(此属性为复杂数据类型)改变时需要手动开启深度监视
}