computed
- 与vue2.x中
computed配置功能一致
- 写法
const person = reactive({
fistName:"Mr",
lastName:"long"
})
let fullName = computed(()=>{
return person.fistName + '-' + person.lastName
})
let fullName = computed({
get(){
return person.fistName + '-' + person.lastName
},
set(value){
const newArr = value.split('-')
person.fistName = newArr[0]
person.lastName = newArr[1]
}
})
watch函数
- 与vue2.x中的配置功能一致
- 两个小坑
- 监视
reactive定义的响应式数据时,oldValue无法获取正确获取,强制开启了deep深度监听(deep设置无效)
- 监视
reactive定义的响应式数据中的某个属性时(这个属性必须是个对象),deep配置有效。
watch(count,(newValue,oldValue)=>{
console.log(newValue,oldValue)
},{immediate:true})
watch([count,name],(newValue,oldValue) =>{
console.log(newValue,oldValue)
})
watch(person,(newValue,oldValue)=>{
console.log(newValue,oldValue)
})
watch(()=>person.name,(newValue,oldValue) =>{
console.log(newValue,oldValue)
})
watch([()=>person.name,()=>person.age],(newValue,oldValue)=>{
console.log(newValue,oldValue)
})
watch(() => person.class,(newValue,oldValue) =>{
console.log(newValue,oldValue)
},{deep:true})
watchEffect
watch的套路是:既要指明监听的属性,也要指明监听的回调函数。
watchEffect的套路是:不需要指明监听的属性,监听中的回调函数用到了那个属性,就监听那个属性。
watchEffect跟computed有点像:
computed注重是计算出来的值,所以必须要有返回值。
watchEffect更注重是过程,所以不用写返回值。
watchEffect(()=>{
const age = person.age
const count = person.count
console.log('watchEffect 配置回调函数执行了。')
})