vue3 ref,shallowRef, triggerRef, customRef
ref深层次响应
变成响应式
const name = ref('refName')
name.value = 'newName'
shallowRef浅层次响应
const obj = shallowRef({ name: 'shallowRefName' })
obj.value = { name: 'newName' } // 响应式
obj.value.name = 'newName' // 非响应式,视图不刷新
triggerRef主动触发一次更新
const obj = shallowRef({ name: 'shallowRefName' })
obj.value = { name: 'newName' } // 响应式
obj.value.name = 'newName' // 非响应式,视图不刷新
triggerRef(obj) // 重新触发一次视图刷新
customRef自定义ref
function custom(value) {
return customRef((track, trigger) => {
return {
get() {
track()
return value
},
set(newVal) {
value = newVal
trigger()
}
}
})
}
// 返回一个ref对象
const name = custom('customRefName')
name.value = 'customNewRefName' // 触发了set方法,视图更新