基本用法
- 返回对象的响应式副本,只能代理对象,不能代理普通值
const obj = reactive({count: 0, name: 'hyh'})
const count = reactive(1)
// value cannot be made reactive: 1
实现原理
reactive
是基于 Proxy
实现的响应式。
const ReactiveFlags = {
SKIP = '__v_skip',
IS_REACTIVE = '__v_isReactive',
IS_READONLY = '__v_isReadonly',
RAW = '__v_raw'
}
// 用于缓存代理过的对象
const proxyMap = new WeakMap();
function createArrayInstrumentations(){
const instrumentations = {};
// proxy([a,b,c]).includes('a')
;['includes', 'indexOf', 'lastIndexOf'].forEach(key =>{
instrumentations[key] = function(this, ...args){
// 将代理对象转化成普通的数组,然后进行依赖收集
const arr = toRaw(this)
for(let i = 0, l = this.length; i < l; i++ ){
// 依赖收集
track(arr, 'get', i + '')
}
// 调用数组原来的方法
const res = arr[key](...args)
// we run the method using the original args first (which may be reactive)
if(res === -1 || res === false){
// 如果没有找到 将参数转化为原始类型重新执行
/*
let obj = {a: 1};
let reactObj = reactive(obj)
const arr1 = reactive([obj])
console.log('arr1.includes(obj) :>> ', arr1.includes(reactObj)); == true
*/
return arr[key](...args.map(toRaw))
}else{
return res
}
}
})
// instrument length-altering mutation methods to avoid length being tracked
// which leads to infinite loops in some cases (#2137)
;['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
instrumentations[key] = function(this, ...args){
pauseTracking();
const res = toRaw(this).apply(this, args)
resetTracking();
return res
}
})
}
function createGetter(isReadonly = false, shallow = false){
return function get(target, key, receiver){
// 判断代理对象是否为数组
const targetIsArray = isArray(target);
if(targetIsArray && hasOwn(arrayInstrumentations, key)){
// 如果是特殊方法,没有进行依赖收集, 而是重写了一些方法
return Reflect.get(arrayInstrumentations, key, receiver)
}
// ...对象处理
}
}
function createSetter(shallow = false){
return function set(target, key, value, receiver){
const oldValue = target[key]
// 判断:是新增还是修改
const hadKey = isArray(target) && isIntegerKey(key)
? Number(key) < target.length
: hasOwn(target, key)
const res = Reflect.set(target, key, value, receiver);
// 触发effect更新
if(!hadKey){
trigger(target, 'add', key, value)
}else{
trigger(target, 'set', key, value, oldValue)
}
}
}
function mutableHandler(){
get: createGetter(),
set: cerateSetter(),
}
function reactive(target){
// 针对特殊场景 reactive(readonly(obj))-> 直接返回readonly即可
if(target && target[ReactiveFlags.IS_READONLY]){
return target
}
return createReactiveObject(target, false, mutaleHandler)
}
function createReactiveObject(target, isReadonly, baseHandler){
if(!isObject(target)){
if (__DEV__) {
console.warn(`value cannot be made reactive: ${String(target)}`)
}
return target
}
// target already has corresponding Proxy
const existingProxy = proxyMap.get(target) // 看目标是否被代理过
if (existingProxy) { // 如果代理过,直接返回代理过的对象
return existingProxy
}
const proxy = new Proxy( // 创建一个proxy对象
target,// 调用对应的handler进行代理
targetType: baseHandlers
)
proxyMap.set(target, proxy) // 存到缓存中
return proxy
}
以上代码只是Vue3的部分源码,简单的实现了reactive的响应式原理。