我们有一个独立的原始值 (例如,一个字符串),我们想让它变成响应式的,Vue 为我们提供了一个可以做相同事情的方法——ref:
import { ref } from 'vue'
const count = ref(0)
console.log(count.value) // 0
count.value++
console.log(count.value) // 1
通过打印可以看到:是一个RefImpl对象
源码搜索发现:
function ref(value) {
return createRef(value, false);
}
function shallowRef(value) {
return createRef(value, true);
}
function createRef(rawValue, shallow) {
if (isRef(rawValue)) {
return rawValue;
}
return new RefImpl(rawValue, shallow);
}
class RefImpl {
constructor(value, __v_isShallow) {
this.__v_isShallow = __v_isShallow;
this.dep = undefined;
this.__v_isRef = true;
this._rawValue = __v_isShallow ? value : toRaw(value);
this._value = __v_isShallow ? value : toReactive(value);
}
get value() {
trackRefValue(this);
return this._value;
}
set value(newVal) {
newVal = this.__v_isShallow ? newVal : toRaw(newVal);
if (shared.hasChanged(newVal, this._rawValue)) {
this._rawValue = newVal;
this._value = this.__v_isShallow ? newVal : toReactive(newVal);
triggerRefValue(this, newVal);
}
}
}
执行顺序:ref()=>createRef()=>new RefImpl()
纳尼?这里还看不出来实现原理,怎么看呢?
通过babel查看编译class的解析原理了,其实es6中class转换后就是defineProperty
可以知道了,ref实现原理就是通过Vue2中熟悉的配方Object.defineProperty来实现的。
const toReactive = (value) => shared.isObject(value) ? reactive(value) : value;
同时通过源码查看发现RefImpl类中的set方法会判断如果是包裹对象的话,会将ref({})中的对象通过reactive包裹起来。
reactive的实现原理就比较直观了上源码:就是通过proxy进行对象的代理实现
function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
if (!shared.isObject(target)) {
{
console.warn(`value cannot be made reactive: ${String(target)}`);
}
return target;
}
// target is already a Proxy, return it.
// exception: calling readonly() on a reactive object
if (target["__v_raw" /* RAW */] &&
!(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
return target;
}
// target already has corresponding Proxy
const existingProxy = proxyMap.get(target);
if (existingProxy) {
return existingProxy;
}
// only specific value types can be observed.
const targetType = getTargetType(target);
if (targetType === 0 /* INVALID */) {
return target;
}
const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
proxyMap.set(target, proxy);
return proxy;
}```