合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
``` export function defineReactive ( obj: Object, key: string, val: any, customSetter?: ?Function, shallow?: boolean ) { // 重点,在给具体属性调用该方法时,都会为该属性生成唯一的dep对象 const dep = new Dep() // 获取该属性的描述对象 const property = Object.getOwnPropertyDescriptor(obj, key) //如果该描述不能被更改,直接返回,因为不能更改,那么就无法代理set和get方法,无法做到响应式 if (property && property.configurable === false) { return } // cater for pre-defined getter/setters const getter = property && property.get const setter = property && property.set let childOb = !shallow && observe(val) // 重新定义data当中的属性,对get和set进行代理。 Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { const value = getter ? getter.call(obj) : val if (Dep.target) { dep.depend() if (childOb) { childOb.dep.depend() if (Array.isArray(value)) { dependArray(value) } } } return value }, set: function reactiveSetter (newVal) { const value = getter ? getter.call(obj) : val /\* eslint-disable no-self-compare \*/ if (newVal === value || (newVal !== newVal && value !== value)) { return } /\* eslint-enable no-self-compare \*/ if (process.env.NODE\_ENV !== 'production' && customSetter) { customSetter() } if (setter) { setter.call(obj, newVal) } else { val = newVal } childOb = !shallow && observe(newVal) dep.notify() } }) } ``` * 在给具体属性调用该方法时,都会为该属性生成唯一的dep对象 * 获取该属性的描述对象,如果该描述configurable为false,直接返回,因为不能更改,那么就无法代理set和get方法,无法做到响应式