Vue3 responsive core reactive source code analysis
1. Reactive source code
1. reactive
Source code path: packages/reactivity/src/reactive.ts
export function reactive(target: object) { // if trying to observe a readonly proxy, return the readonly version. // 是否是只读响应式对象 if (isReadonly(target)) { return target } return createReactiveObject( target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap ) }
When we execute When reactive({})
, the createReactiveObject
factory method will be executed and a responsive object will be returned.
2. Next, look at the factory method createReactiveObject
Source code path: packages/reactivity/src/reactive.ts
function createReactiveObject( target: Target, isReadonly: boolean, baseHandlers: ProxyHandler<any>, collectionHandlers: ProxyHandler<any>, proxyMap: WeakMap<Target, any> ) { // 仅对对象类型有效(对象、数组和 Map、Set 这样的集合类型),而对 string、number 和 boolean 这样的 原始类型 无效。 if (!isObject(target)) { if (__DEV__) { 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[ReactiveFlags.RAW] && !(isReadonly && target[ReactiveFlags.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 === TargetType.INVALID) { return target } const proxy = new Proxy( target, targetType === TargetType.COLLECTION ? collectionHandlers : baseHandlers ) proxyMap.set(target, proxy) return proxy }
is only valid for object types ( Objects, arrays, and collection types such as Map and Set), but not valid for primitive types such as string, number, and boolean.
if (!isObject(target)) { if (__DEV__) { console.warn(`value cannot be made reactive: ${String(target)}`) } return target }
If the target is already a proxy object, then return the target directly
if ( target[ReactiveFlags.RAW] && !(isReadonly && target[ReactiveFlags.IS_REACTIVE]) ) { return target }
If the target already has a corresponding proxy object, then return the proxy object directly
const existingProxy = proxyMap.get(target) // 存储响应式对象 if (existingProxy) { return existingProxy }
For For types that cannot be observed, the target is returned directly
const targetType = getTargetType(target) if (targetType === TargetType.INVALID) { return target }
// getTargetType源码 function getTargetType(value: Target) { return value[ReactiveFlags.SKIP] || !Object.isExtensible(value) // 不可扩展 ? TargetType.INVALID : targetTypeMap(toRawType(value)) } // ReactiveFlags枚举 export const enum ReactiveFlags { // 用于标识一个对象是否不可被转为代理对象,对应的值是 __v_skip SKIP = '__v_skip', // 用于标识一个对象是否是响应式的代理,对应的值是 __v_isReactive IS_REACTIVE = '__v_isReactive', // 用于标识一个对象是否是只读的代理,对应的值是 __v_isReadonly IS_READONLY = '__v_isReadonly', // 用于标识一个对象是否是浅层代理,对应的值是 __v_isShallow IS_SHALLOW = '__v_isShallow', // 用于保存原始对象的 key,对应的值是 __v_raw RAW = '__v_raw' } // targetTypeMap function targetTypeMap(rawType: string) { switch (rawType) { case 'Object': case 'Array': return TargetType.COMMON case 'Map': case 'Set': case 'WeakMap': case 'WeakSet': return TargetType.COLLECTION default: return TargetType.INVALID } } // toRawType export const toRawType = (value: unknown): string => { // extract "RawType" from strings like "[object RawType]" return toTypeString(value).slice(8, -1) }
Creating a responsive object (core code)
const proxy = new Proxy( target, targetType === TargetType.COLLECTION ? collectionHandlers : baseHandlers )
Next, we will focus on the baseHandlers
callback function.
2. baseHandlers
1, baseHandlers
baseHandlers
is mutableHandlers
, from the baseHandlers
file .
The source code of mutableHandlers is as follows, which proxies get, set, deleteProperty, has, and ownKeys respectively.
export const mutableHandlers: ProxyHandler<object> = { get, set, deleteProperty, has, ownKeys }
Let’s take a look at the specific implementation of these interceptors.
(1), get proxy
const get = /*#__PURE__*/ createGetter() function createGetter(isReadonly = false, shallow = false) { // 闭包返回 get 拦截器方法 return function get(target: Target, key: string | symbol, receiver: object) { // 如果访问的是 __v_isReactive 属性,那么返回 isReadonly 的取反值 if (key === ReactiveFlags.IS_REACTIVE) { return !isReadonly // 如果访问的是 __v_isReadonly 属性,那么返回 isReadonly 的值 } else if (key === ReactiveFlags.IS_READONLY) { return isReadonly // 如果访问的是 __v_isShallow 属性,那么返回 shallow 的值 } else if (key === ReactiveFlags.IS_SHALLOW) { return shallow // 如果访问的是 __v_raw 属性,那么返回 target } else if ( key === ReactiveFlags.RAW && receiver === (isReadonly ? shallow ? shallowReadonlyMap : readonlyMap : shallow ? shallowReactiveMap : reactiveMap ).get(target) ) { return target } // target是否是数组 const targetIsArray = isArray(target) if (!isReadonly) { // 可读 // 如果是数组,并且访问的是数组的一些方法,那么返回对应的方法 /** * Vue3中使用 arrayInstrumentations对数组的部分方法做了处理,为什么要这么做呢? * 对于 push、pop、 shift、 unshift、 splice 这些方法, * 写入和删除时底层会获取当前数组的length属性,如果我们在effect中使用的话, * 会收集length属性的依赖,当使用这些api是也会更改length,就会造成死循环: * */ if (targetIsArray && hasOwn(arrayInstrumentations, key)) { // 返回重写的push、pop、 shift、 unshift、 splice 'includes', 'indexOf', 'lastIndexOf' return Reflect.get(arrayInstrumentations, key, receiver) } // 如果访问的是 hasOwnProperty 方法,那么返回 hasOwnProperty 方法 if (key === 'hasOwnProperty') { return hasOwnProperty } } // 获取 target 的 key 属性值 const res = Reflect.get(target, key, receiver) // 如果是内置的 Symbol,或者是不可追踪的 key,那么直接返回 res if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) { return res } // 如果不是只读的,那么进行依赖收集 if (!isReadonly) { track(target, TrackOpTypes.GET, key) } // 如果是浅的,那么直接返回 res if (shallow) { return res } // 如果 res 是 ref,对返回的值进行解包 if (isRef(res)) { // ref unwrapping - skip unwrap for Array + integer key. return targetIsArray && isIntegerKey(key) ? res : res.value } // 如果 res 是对象,递归代理 if (isObject(res)) { // Convert returned value into a proxy as well. we do the isObject check // here to avoid invalid value warning. Also need to lazy access readonly // and reactive here to avoid circular dependency. return isReadonly ? readonly(res) : reactive(res) } return res } }
When the target is an array, 'push', 'pop', 'shift', 'unshift', ' These methods of splice' will change the length of the array and cause infinite recursion. Therefore, the collection of dependencies must be paused first, so the above methods of the array are intercepted and rewritten.
if (targetIsArray && hasOwn(arrayInstrumentations, key)) { // 返回重写的push、pop、 shift、 unshift、 splice 'includes', 'indexOf', 'lastIndexOf' return Reflect.get(arrayInstrumentations, key, receiver) }
Rewritten code:
const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations() function createArrayInstrumentations() { const instrumentations: Record<string, Function> = {} // instrument length-altering mutation methods to avoid length being tracked // which leads to infinite loops in some cases (#2137) ;(['push', 'pop', 'shift', 'unshift', 'splice'] as const).forEach(key => { instrumentations[key] = function (this: unknown[], ...args: unknown[]) { // 由于上面的方法会改变数组长度,因此暂停收集依赖,不然会导致无限递归 console.log('----自定义push等入口:this, args, key'); pauseTracking() console.log('----自定义push等暂停收集依赖&执行开始') // 调用原始方法 const res = (toRaw(this) as any)[key].apply(this, args) console.log('----自定义push等暂停收集依赖&执行结束') //复原依赖收集 resetTracking() return res } }) return instrumentations }
The following picture is the execution result:
can be understood with the following code:
let arr = [1,2,3] let obj = { 'push': function(...args) { // 暂停收集依赖逻辑 return Array.prototype.push.apply(this, [...args]) // 启动收集依赖逻辑 } } let proxy = new Proxy(arr, { get: function (target, key, receiver) { console.log('get的key为 ===>' + key); let res = ''; if(key === 'push') { //重写push res = Reflect.get(obj, key, receiver) } else { res = Reflect.get(target, key, receiver) } return res }, set(target, key, value, receiver){ console.log('set的key为 ===>' + key, value); return Reflect.set(target, key, value, receiver); } }) proxy.push('99')
Special attributes are not subject to dependency collection
// 如果是内置的 Symbol,或者是不可追踪的 key,那么直接返回 res if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) { return res; }
This step is to filter some special attributes, such as native Symbol type attributes, such as: Symbol.iterator, Symbol.toStringTag, etc. These attributes do not require dependency collection because they are built-in and will not change;
There are also some untraceable attributes, such as: proto, __v_isRef, __isVue. These attributes do not require dependency collection;
Dependency collection
// 如果不是只读的,那么进行依赖收集 if (!isReadonly) { track(target, "get" /* TrackOpTypes.GET */, key); }
Shallow does not perform recursive proxy
if (shallow) { return res; }
Unpack the return value
// 如果 res 是 ref,对返回的值进行解包 if (isRef(res)) { // 对于数组和整数类型的 key,不进行解包 return targetIsArray && isIntegerKey(key) ? res : res.value; }
This step is to handle the ref situation. If res is ref, then unpack the res. Here are A judgment, if it is an array and the key is an integer type, then it will not be unpacked; because reactive is deeply responsive, it must be unpacked if the attribute is ref
Recursive proxy of the object
// 如果 res 是对象,那么对返回的值进行递归代理 if (isObject(res)) { return isReadonly ? readonly(res) : reactive(res); }
(2), set agent
const set = /*#__PURE__*/ createSetter() function createSetter(shallow = false) { // 返回一个set方法 return function set( target: object, key: string | symbol, value: unknown, receiver: object ): boolean { let oldValue = (target as any)[key] // 获取旧值 // 如果旧值是只读的,并且是 ref,并且新值不是 ref if (isReadonly(oldValue) && isRef(oldValue) && !isRef(value)) { return false } if (!shallow) { // 非shallow // 新值非shallow && 非只读 if (!isShallow(value) && !isReadonly(value)) { // 获取新旧值的原始值 oldValue = toRaw(oldValue) value = toRaw(value) } // 代理对象非数组 & 旧值是ref & 新值非ref if (!isArray(target) && isRef(oldValue) && !isRef(value)) { oldValue.value = value return true } } else { // in shallow mode, objects are set as-is regardless of reactive or not } console.log('----set', target, key, value) // 是数组 & key是整型数字 ? // 如果 key 小于数组的长度,那么就是有这个 key : // 如果不是数组,那么就是普通对象,直接判断是否有这个 key // 数组会触发两次set: index和新增的值 和 'length'和新增之后的数组长度 const hadKey = isArray(target) && isIntegerKey(key) ? Number(key) < target.length : hasOwn(target, key) // 设置key-value const result = Reflect.set(target, key, value, receiver) // don't trigger if target is something up in the prototype chain of original // 如果目标对象是原始数据的原型链中的某个元素,则不会触发依赖收集 if (target === toRaw(receiver)) { if (!hadKey) {// 如果没有这个 key,那么就是新增了一个属性,触发 add 事件 trigger(target, TriggerOpTypes.ADD, key, value) } else if (hasChanged(value, oldValue)) { // // 如果有这个 key,那么就是修改了一个属性,触发 set 事件 trigger(target, TriggerOpTypes.SET, key, value, oldValue) } } // 返回结果,这个结果为 boolean 类型,代表是否设置成功 return result } }
Main logic:
Get the old value
let oldValue = target[key];
Judge whether the old value is only Read
// 如果旧值是只读的,并且是 ref,并且新值不是 ref,那么直接返回 false,代表设置失败 if (isReadonly(oldValue) && isRef(oldValue) && !isRef(value)) { return false; }
The above is the detailed content of Vue3 responsive core reactive source code analysis. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

vue3+vite:src uses require to dynamically import images and error reports and solutions. vue3+vite dynamically imports multiple images. If vue3 is using typescript development, require will introduce image errors. requireisnotdefined cannot be used like vue2 such as imgUrl:require(' .../assets/test.png') is imported because typescript does not support require, so import is used. Here is how to solve it: use awaitimport

tinymce is a fully functional rich text editor plug-in, but introducing tinymce into vue is not as smooth as other Vue rich text plug-ins. tinymce itself is not suitable for Vue, and @tinymce/tinymce-vue needs to be introduced, and It is a foreign rich text plug-in and has not passed the Chinese version. You need to download the translation package from its official website (you may need to bypass the firewall). 1. Install related dependencies npminstalltinymce-Snpminstall@tinymce/tinymce-vue-S2. Download the Chinese package 3. Introduce the skin and Chinese package. Create a new tinymce folder in the project public folder and download the

Vue implements the blog front-end and needs to implement markdown parsing. If there is code, it needs to implement code highlighting. There are many markdown parsing libraries for Vue, such as markdown-it, vue-markdown-loader, marked, vue-markdown, etc. These libraries are all very similar. Marked is used here, and highlight.js is used as the code highlighting library. The specific implementation steps are as follows: 1. Install dependent libraries. Open the command window under the vue project and enter the following command npminstallmarked-save//marked to convert markdown into htmlnpmins

To achieve partial refresh of the page, we only need to implement the re-rendering of the local component (dom). In Vue, the easiest way to achieve this effect is to use the v-if directive. In Vue2, in addition to using the v-if instruction to re-render the local dom, we can also create a new blank component. When we need to refresh the local page, jump to this blank component page, and then jump back in the beforeRouteEnter guard in the blank component. original page. As shown in the figure below, how to click the refresh button in Vue3.X to reload the DOM within the red box and display the corresponding loading status. Since the guard in the component in the scriptsetup syntax in Vue3.X only has o

After the vue3 project is packaged and published to the server, the access page displays blank 1. The publicPath in the vue.config.js file is processed as follows: const{defineConfig}=require('@vue/cli-service') module.exports=defineConfig({publicPath :process.env.NODE_ENV==='production'?'./':'/&

Preface Whether it is vue or react, when we encounter multiple repeated codes, we will think about how to reuse these codes instead of filling a file with a bunch of redundant codes. In fact, both vue and react can achieve reuse by extracting components, but if you encounter some small code fragments and you don’t want to extract another file, in comparison, react can be used in the same Declare the corresponding widget in the file, or implement it through renderfunction, such as: constDemo:FC=({msg})=>{returndemomsgis{msg}}constApp:FC=()=>{return(

Using Vue to build custom elements WebComponents is a collective name for a set of web native APIs that allow developers to create reusable custom elements (customelements). The main benefit of custom elements is that they can be used with any framework, even without one. They are ideal when you are targeting end users who may be using a different front-end technology stack, or when you want to decouple the final application from the implementation details of the components it uses. Vue and WebComponents are complementary technologies, and Vue provides excellent support for using and creating custom elements. You can integrate custom elements into existing Vue applications, or use Vue to build

1 Introduction 1.1 Purpose ElementPlus uses on-demand introduction to greatly reduce the size of the packaged file. 1.2 The final effect is to automatically generate the components.d.ts file and introduce it into the file. The ElementPlus component automatically generates the components.d.ts file and introduce it into the file. ElementPlusAPI2 Preparation Install ElementPlus#Choose a package manager you like#NPM$npminstallelement-plus--save#Yarn$yarnaddelement-plus#pnpm$pnpminstallelement-plus3 Press
