This article shares 12 high-frequency Vue principle interview questions, covering the core implementation principles of Vue. In fact, it is impossible to explain the implementation principles of a framework in one article. I hope that through these 12 This question allows readers to have a certain understanding of their own Vue mastery (number B), so as to make up for their own shortcomings and better master Vue.
【Related recommendations:vue interview questions(2021)】
##Core implementation class: Observer: its The function is to add getters and setters to the properties of the object for dependency collection and dispatch updates Dep: used to collect dependencies of the current responsive object. Each responsive object, including sub-objects, has a Dep instance. (subs inside is an array of Watcher instances). When the data changes, each watcher will be notified through dep.notify(). Watcher: Observer object, the instance is divided into three types: rendering watcher (render watcher), calculated attribute watcher (computed watcher), listener watcher (user watcher) Watcher and Dep Dep is instantiated in the relationship watcher and adds subscribers to dep.subs. dep traverses dep.subs through notify to notify each watcher update. Dependency collection
Vue wants to ensure that not only the value that the calculated property depends on changes, but when the final calculated value of the calculated property changes, the rendering watcher will be triggered to re-render, which is essentially an optimization.)
If not, just set this.dirty = true. (When a calculated attribute depends on other data, the attribute will not be recalculated immediately. It will only be actually calculated when other places need to read the attribute later, that is, it has lazy (lazy calculation) characteristics.)
No caching, similar to the monitoring callback of certain data, the callback will be executed whenever the monitored data changes Follow up.
Application scenario Application scenario: When we need to perform numerical calculations and depend on other data, computed should be used, because the cache feature of computed can be used to avoid Each time a value is obtained, it is recalculated.When we need to perform asynchronous or expensive operations when the data changes, we should use watch. Using the watch option allows us to perform an asynchronous operation (access an API), limit the frequency with which we perform the operation, and when we get Before the final result, set the intermediate state. These are things that computed properties cannot do.
Object.defineProperty itself has a certain ability to monitor changes in array subscripts, but in Vue, considering the cost-effectiveness of performance/experience, Youda abandoned this feature ( Why can’t Vue detect array changes). In order to solve this problem, after Vue internal processing, you can use the following methods to monitor the array
push(); pop(); shift(); unshift(); splice(); sort(); reverse();
Since only the above 7 methods are hacked, the properties of other arrays cannot be detected. It still has certain limitations.
Object.defineProperty can only hijack the properties of an object, so we need to traverse each property of each object. In Vue 2.x, data monitoring is achieved by recursively traversing the data object. If the attribute value is also an object, then deep traversal is required. Obviously, it is a better choice if a complete object can be hijacked.Proxy can hijack the entire object and return a new object. Proxy can not only proxy objects, but also proxy arrays. You can also proxy dynamically added attributes.
key is the unique id given to each vnode. Depending on the key, our diff operation can be more accurate and faster (the diff node is also faster for simple list page rendering, but There will be some hidden side effects, such as the transition effect may not be produced, or some nodes have bound data (form) states, and state misalignment will occur.)
Diff algorithm will first be performed Cross-compare the head and tail of the old and new nodes. When there is no match, the new node's key will be used to compare with the old node to find the corresponding old node.
is more accurate: because with the key, it is not reused in place. , in-place reuse can be avoided in the sameNode function a.key === b.key comparison. Therefore, it will be more accurate. If the key is not added, the status of the previous node will be retained, which will produce a series of bugs.
Faster: The uniqueness of key can be fully utilized by the Map data structure. Compared with the time complexity of traversal search O(n), the time complexity of Map is only O(1). The source code is as follows:
function createKeyToOldIdx(children, beginIdx, endIdx) { let i, key; const map = {}; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) map[key] = i; } return map; }
JS operating mechanism
JS execution is single-threaded and it is based on the event loop. The event loop is roughly divided into the following steps:
The execution process of the main thread is one tick, and all asynchronous results are scheduled through the "task queue". The message queue stores tasks one by one. The specification stipulates that tasks are divided into two categories, namely macro tasks and micro tasks, and after each macro task ends, all micro tasks must be cleared.
for (macroTask of macroTaskQueue) { // 1. Handle current MACRO-TASK handleMacroTask(); // 2. Handle all MICRO-TASK for (microTask of microTaskQueue) { handleMicroTask(microTask); } }
In the browser environment:
Common macro tasks includesetTimeout, MessageChannel, postMessage, setImmediate
Common micro tasks includeMutationObsever and Promise.then
Asynchronous update queue
Maybe you haven’t noticed yet, Vue is# when updating the DOM ##AsynchronousExecuted. As long as it listens for data changes, Vue will open a queue and buffer all data changes that occur in the same event loop.
If the same watcher is triggered multiple times, it will only be pushed into the queue once. This deduplication during buffering is important to avoid unnecessary calculations and DOM operations. Then, on the next event loop "tick", Vue flushes the queue and performs the actual (deduplicated) work. Vue internally tries to use native Promise.then, MutationObserver and setImmediate for asynchronous queues. If the execution environment does not support it, setTimeout(fn, 0) will be used instead.In the source code of vue2.5, the macrotask downgrade scheme is: setImmediate, MessageChannel, setTimeout
vue 的 nextTick 方法的实现原理:
我们先来看看源码
const arrayProto = Array.prototype; export const arrayMethods = Object.create(arrayProto); const methodsToPatch = [ "push", "pop", "shift", "unshift", "splice", "sort", "reverse" ]; /** * Intercept mutating methods and emit events */ methodsToPatch.forEach(function(method) { // cache original method const original = arrayProto[method]; def(arrayMethods, method, function mutator(...args) { const result = original.apply(this, args); const ob = this.__ob__; let inserted; switch (method) { case "push": case "unshift": inserted = args; break; case "splice": inserted = args.slice(2); break; } if (inserted) ob.observeArray(inserted); // notify change ob.dep.notify(); return result; }); }); /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray(items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } };
简单来说,Vue 通过原型拦截的方式重写了数组的 7 个方法,首先获取到这个数组的ob,也就是它的 Observer 对象,如果有新的值,就调用 observeArray 对新的值进行监听,然后手动调用 notify,通知 render watcher,执行 update
new Vue()实例中,data 可以直接是一个对象,为什么在 vue 组件中,data 必须是一个函数呢?
因为组件是可以复用的,JS 里对象是引用关系,如果组件 data 是一个对象,那么子组件中的 data 属性值会互相污染,产生副作用。
所以一个组件的 data 选项必须是一个函数,因此每个实例可以维护一份被返回对象的独立的拷贝。new Vue 的实例是不会被复用的,因此不存在以上问题。
Vue 事件机制 本质上就是 一个 发布-订阅 模式的实现。
class Vue { constructor() { // 事件通道调度中心 this._events = Object.create(null); } $on(event, fn) { if (Array.isArray(event)) { event.map(item => { this.$on(item, fn); }); } else { (this._events[event] || (this._events[event] = [])).push(fn); } return this; } $once(event, fn) { function on() { this.$off(event, on); fn.apply(this, arguments); } on.fn = fn; this.$on(event, on); return this; } $off(event, fn) { if (!arguments.length) { this._events = Object.create(null); return this; } if (Array.isArray(event)) { event.map(item => { this.$off(item, fn); }); return this; } const cbs = this._events[event]; if (!cbs) { return this; } if (!fn) { this._events[event] = null; return this; } let cb; let i = cbs.length; while (i--) { cb = cbs[i]; if (cb === fn || cb.fn === fn) { cbs.splice(i, 1); break; } } return this; } $emit(event) { let cbs = this._events[event]; if (cbs) { const args = [].slice.call(arguments, 1); cbs.map(item => { args ? item.apply(this, args) : item.call(this); }); } return this; } }
export default { name: "keep-alive", abstract: true, // 抽象组件属性 ,它在组件实例建立父子关系的时候会被忽略,发生在 initLifecycle 的过程中 props: { include: patternTypes, // 被缓存组件 exclude: patternTypes, // 不被缓存组件 max: [String, Number] // 指定缓存大小 }, created() { this.cache = Object.create(null); // 缓存 this.keys = []; // 缓存的VNode的键 }, destroyed() { for (const key in this.cache) { // 删除所有缓存 pruneCacheEntry(this.cache, key, this.keys); } }, mounted() { // 监听缓存/不缓存组件 this.$watch("include", val => { pruneCache(this, name => matches(val, name)); }); this.$watch("exclude", val => { pruneCache(this, name => !matches(val, name)); }); }, render() { // 获取第一个子元素的 vnode const slot = this.$slots.default; const vnode: VNode = getFirstComponentChild(slot); const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions; if (componentOptions) { // name不在inlcude中或者在exlude中 直接返回vnode // check pattern const name: ?string = getComponentName(componentOptions); const { include, exclude } = this; if ( // not included (include && (!name || !matches(include, name))) || // excluded (exclude && name && matches(exclude, name)) ) { return vnode; } const { cache, keys } = this; // 获取键,优先获取组件的name字段,否则是组件的tag const key: ?string = vnode.key == null ? // same constructor may get registered as different local components // so cid alone is not enough (#3269) componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : "") : vnode.key; // 命中缓存,直接从缓存拿vnode 的组件实例,并且重新调整了 key 的顺序放在了最后一个 if (cache[key]) { vnode.componentInstance = cache[key].componentInstance; // make current key freshest remove(keys, key); keys.push(key); } // 不命中缓存,把 vnode 设置进缓存 else { cache[key] = vnode; keys.push(key); // prune oldest entry // 如果配置了 max 并且缓存的长度超过了 this.max,还要从缓存中删除第一个 if (this.max && keys.length > parseInt(this.max)) { pruneCacheEntry(cache, keys[0], keys, this._vnode); } } // keepAlive标记位 vnode.data.keepAlive = true; } return vnode || (slot && slot[0]); } };
原理
LRU 缓存淘汰算法
LRU(Least recently used)算法根据数据的历史访问记录来进行淘汰数据,其核心思想是“如果数据最近被访问过,那么将来被访问的几率也更高”。
keep-alive 的实现正是用到了 LRU 策略,将最近访问的组件 push 到 this.keys 最后面,this.keys[0]也就是最久没被访问的组件,当缓存实例超过 max 设置值,删除 this.keys[0]
受现代 JavaScript 的限制 (而且 Object.observe 也已经被废弃),Vue 无法检测到对象属性的添加或删除。
由于 Vue 会在初始化实例时对属性执行 getter/setter 转化,所以属性必须在 data 对象上存在才能让 Vue 将它转换为响应式的。
对于已经创建的实例,Vue 不允许动态添加根级别的响应式属性。但是,可以使用 Vue.set(object, propertyName, value) 方法向嵌套对象添加响应式属性。
那么 Vue 内部是如何解决对象新增属性不能响应的问题的呢?
export function set(target: Array| Object, key: any, val: any): any { // target 为数组 if (Array.isArray(target) && isValidArrayIndex(key)) { // 修改数组的长度, 避免索引>数组长度导致splice()执行有误 target.length = Math.max(target.length, key); // 利用数组的splice变异方法触发响应式 target.splice(key, 1, val); return val; } // target为对象, key在target或者target.prototype上 且必须不能在 Object.prototype 上,直接赋值 if (key in target && !(key in Object.prototype)) { target[key] = val; return val; } // 以上都不成立, 即开始给target创建一个全新的属性 // 获取Observer实例 const ob = (target: any).__ob__; // target 本身就不是响应式数据, 直接赋值 if (!ob) { target[key] = val; return val; } // 进行响应式处理 defineReactive(ob.value, key, val); ob.dep.notify(); return val; }
本文转载自:https://segmentfault.com/a/1190000021407782
推荐教程:《JavaScript视频教程》
The above is the detailed content of 12 Vue high-frequency principle interview questions (with analysis). For more information, please follow other related articles on the PHP Chinese website!