- 文件目录:packages/reactivity/src/ref.ts
- 核心函数:createRef
- 解读:使用的时候,通过 xxx.value取值, xxx.value=aaa赋值。优点:可以直接赋值value,可以重新定义对象的响应式属性,而且也会触发依赖更新,重新收集新对象的依赖
function createRef(rawValue, shallow) {
if (isRef(rawValue)) {
return rawValue
}
return new RefImpl(rawValue, shallow)
}
class RefImpl {
constructor(value, isShallow) {
this._rawValue = isShallow ? value : toRaw(value)
this._value = isShallow ? value : toReactive(value)
}
get value() {
track()
return this._value
}
set value(newValue) {
const useDirectValue = this[ReactiveFlags.IS_SHALLOW] || isShallow(newValue) || isReadonly(newValue)
newValue = useDirectValue ? newValue : toRaw(newValue)
this.value = useDirectValue ? newValue : toReactive(newValue)
if (hasChanged(newVal, this._rawValue)) {
this._rawValue = newVal
this._value = useDirectValue ? newVal : toReactive(newVal)
trigger(this, newVal)
}
}
}
function toReactive(value) {
isObject(value) ? reactive(value) : value
}