1.computed的使用
const firstName = ref('andy')
const lastName = ref('jack')
//用法一:传入函数直接计算
const fullName = computed(() => firstName.value + ' ' + lastName.value)
//用法二:在对象里传入get和set方法
const fullName = computed({
get: () => firstName.value + ' ' + lastName.value,
set(newValue) {
const names = newValue.split(' ')
firstName.value = names[0]
lastName.value = names[1]
},
})
const changeName = () => {
//fullName也是ref对象
fullName.value = 'mask ami'
}
总的来说和vue2中的用法差别不大
2.watcEffect的使用
const name = ref('jack')
const age = ref('18')
const changeName = () => (name.value = 'mask')
const changeAge = () => {
age.value++
if (age.value > 25) {
//满足条件停止侦听
stop()
}
}
//自动收集响应式的依赖
//返回一个停止器
const stop = watchEffect((onInValidate) => {
//类似拦截器功能,可以取消重复的网络请求,
//或者在网络请求没有到达前取消了相应的侦听,在这个函数中就可以取消当前的网络请求
onInValidate(() => {
console.log(111)
})
//监听name和age的值
console.log('name', name.value, 'age', age.value)
})
3.watch的使用
用法一
const info = reactive({ name: 'jack', age: 18 })
//用法一:传入一个get函数
watch(
() => info.name,
(newValue, oldValue) => {
console.log('newValue:', newValue, 'oldValue:', oldValue)
}
)
const changeName = () => {
info.name = 'jim'
}
结果

用法二
//用法二:传入一个reactive对象
//newValue和oldvalue获取到的都是reactive对象
watch(info, (newValue, oldValue) => {
console.log('newValue:', newValue, 'oldValue:', oldValue)
})
const changeName = () => {
info.name = 'jim'
}
结果

获取到的/newValue和oldvalue都是Proxy
//如果希望newValue和oldvalue获取到的是普通对象,将传入的对象进行拷贝
watch(
() => {
return { ...info }
},
(newValue, oldValue) => {
console.log('newValue:', newValue, 'oldValue:', oldValue)
}
)
const changeName = () => {
info.name = 'jim'
}
结果

获取到的/newValue和oldvalue都是普通对象
用法三
const name = ref('jack')
// 用法三:传入一个ref对象
watch(name, (newValue, oldValue) => {
console.log('newValue:', newValue, 'oldValue:', oldValue)
})
const changeName = () => {
name.value = 'jim'
}
结果

侦听多个数据源
//监听多个数据源,利用数组可以传入不同或者相同类型的值
watch(
[
() => {
return { ...info }
},
name,
],
//如果想拿具体值可以将newValue和oldvalue进行解构
(newValue, oldValue) => {
console.log('newValue:', newValue, 'oldValue:', oldValue)
}
)
const changeName = () => {
info.name = 'mask'
name.value = 'jim'
}
结果

深度侦听
//直接传入reactive对象是默认可以进行深度侦听
const info1 = reactive({ name: 'jack', age: 18, friend: { name: 'mask' } })
watch(info1, (newValue, oldValue) => {
console.log('newValue:', newValue, 'oldValue:', oldValue)
})
const changeName = () => {
info1.name = 'mask'
}
结果

//如果传入一个get函数 是不能进行一个深度侦听,需要配置watch的第三个参数
watch(
() => {
return { ...info1 }
},
(newValue, oldValue) => {
console.log('newValue:', newValue, 'oldValue:', oldValue)
},
{
deep: true, //是否深度侦听
immediate: true, //是否立即执行
}
)
const changeName = () => {
info1.friend.name = 'jack'
}
结果

第一次立即执行,所以oldValue是undefined,执行changeName之后friend.name都是相同的值
生命周期函数
用法和opitiosAPI的使用方法差不多,只是声明时要在前面加上on,由于vue内部优先调用setup函数,所有前两个声命周期函数是不必须的,在setup函数里面就能实现相同的效果

网友评论