This article summarizes some 2023 selected vue high-frequency interview questions (with answers) worth collecting. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
(Learning video sharing: vue video tutorial )
Object.defineProperty itself has a certain ability to monitor changes in array subscripts, but in Vue, from the perspective of performance/experience cost-effectiveness, Youda has 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.
If you don’t use key, Vue will use a method that minimizes dynamic elements and tries to in-place as much as possible Algorithms that modify/reuse elements of the same type. Key is the only mark for vnode in Vue. Through this key, our diff operation can be more accurate and faster
More accurate: Because with key, it is not In-place reuse can be avoided in the sameNode function a.key === b.key comparison. So it will be more accurate.
Faster: Use the uniqueness of the key to generate a map object to obtain the corresponding node, which is faster than the traversal method
Involves the template compilation principle in Vue, the main process:
Convert the template into ast
Tree, ast
Use objects to describe the real JS syntax (convert real DOM into virtual DOM)
Optimize tree
Put ast
tree generation code
Vue
is a component-level update. If asynchronous updates are not used, the current component will be re-rendered every time the data is updated, so for the sake of performance, Vue
The view will be updated asynchronously after this round of data update. Core Idea nextTick
.
dep.notify()
Notify the watcher to update, subs[i].update
Call the watcher's update
, queueWatcher in sequence
Put the watcher into the queue, and nextTick ( flushSchedulerQueue
) refreshes the watcher queue in the next tick (asynchronously).
Objects are reference types. When reusing components, since the data objects all point to the same data object, when data is modified in one component, data in other reused components will be modified at the same time. ; When using a function that returns an object, since each time a new object (an instance of Object) is returned and the reference address is different, this problem will not occur.
MVC
MVC’s full name is Model View Controller, which is model-view (view) - the abbreviation of controller, a software design model
The idea of MVC: One sentence description is that the Controller is responsible for displaying the Model's data using the View. In other words It is to assign the Model data to the View in the Controller.
MVVM
MVVM has added a new VM class
MVVM 与 MVC 最大的区别就是:它实现了 View 和 Model 的自动同步,也就是当 Model 的属性改变时,我们不用再自己手动操作 Dom 元素,来改变 View 的显示,而是改变属性后该属性对应 View 层显示会自动改变(对应Vue数据驱动的思想)
整体看来,MVVM 比 MVC 精简很多,不仅简化了业务与界面的依赖,还解决了数据频繁更新的问题,不用再用选择器操作 DOM 元素。因为在 MVVM 中,View 不知道 Model 的存在,Model 和 ViewModel 也观察不到 View,这种低耦合模式提高代码的可重用性
注意:Vue 并没有完全遵循 MVVM 的思想 这一点官网自己也有说明
那么问题来了 为什么官方要说 Vue 没有完全遵循 MVVM 思想呢?
- 严格的 MVVM 要求 View 不能和 Model 直接通信,而 Vue 提供了$refs 这个属性,让 Model 可以直接操作 View,违反了这一规定,所以说 Vue 没有完全遵循 MVVM。
1)Vue为什么要用vm.$set() 解决对象新增属性不能响应的问题
Vue使用了Object.defineProperty实现双向数据绑定
在初始化实例时对属性执行 getter/setter 转化
属性必须在data对象上存在才能让Vue将它转换为响应式的(这也就造成了Vue无法检测到对象属性的添加或删除)
所以Vue提供了Vue.set (object, propertyName, value) / vm.$set (object, propertyName, value)
2)接下来我们看看框架本身是如何实现的呢?
Vue 源码位置:vue/src/core/instance/index.js
export function set (target: Array<any> | Object, key: any, val: any): any { // target 为数组 if (Array.isArray(target) && isValidArrayIndex(key)) { // 修改数组的长度, 避免索引>数组长度导致splcie()执行有误 target.length = Math.max(target.length, key) // 利用数组的splice变异方法触发响应式 target.splice(key, 1, val) return val } // key 已经存在,直接修改属性值 if (key in target && !(key in Object.prototype)) { target[key] = val return val } const ob = (target: any).__ob__ // target 本身就不是响应式数据, 直接赋值 if (!ob) { target[key] = val return val } // 对属性进行响应式处理 defineReactive(ob.value, key, val) ob.dep.notify() return val }
我们阅读以上源码可知,vm.$set 的实现原理是:
如果目标是数组,直接使用数组的 splice 方法触发相应式;
如果目标是对象,会先判读属性是否存在、对象是否是响应式,
最终如果要对属性进行响应式处理,则是通过调用 defineReactive 方法进行响应式处理
defineReactive 方法就是 Vue 在初始化对象时,给对象属性采用 Object.defineProperty 动态添加 getter 和 setter 的功能所调用的方法
Vue3.x 改用 Proxy 替代 Object.defineProperty。因为 Proxy 可以直接监听对象和数组的变化,并且有多达 13 种拦截方法。
相关代码如下
import { mutableHandlers } from "./baseHandlers"; // 代理相关逻辑 import { isObject } from "./util"; // 工具方法 export function reactive(target) { // 根据不同参数创建不同响应式对象 return createReactiveObject(target, mutableHandlers); } function createReactiveObject(target, baseHandler) { if (!isObject(target)) { return target; } const observed = new Proxy(target, baseHandler); return observed; } const get = createGetter(); const set = createSetter(); function createGetter() { return function get(target, key, receiver) { // 对获取的值进行放射 const res = Reflect.get(target, key, receiver); console.log("属性获取", key); if (isObject(res)) { // 如果获取的值是对象类型,则返回当前对象的代理对象 return reactive(res); } return res; }; } function createSetter() { return function set(target, key, value, receiver) { const oldValue = target[key]; const hadKey = hasOwn(target, key); const result = Reflect.set(target, key, value, receiver); if (!hadKey) { console.log("属性新增", key, value); } else if (hasChanged(value, oldValue)) { console.log("属性值被修改", key, value); } return result; }; } export const mutableHandlers = { get, // 当获取属性时调用此方法 set, // 当修改属性时调用此方法 };
简单说,Vue的编译过程就是将template
转化为render
函数的过程。会经历以下阶段:
首先解析模版,生成AST语法树
(一种用JavaScript对象的形式来描述整个模板)。 使用大量的正则表达式对模板进行解析,遇到标签、文本的时候都会执行对应的钩子进行相关处理。
Vue的数据是响应式的,但其实模板中并不是所有的数据都是响应式的。有一些数据首次渲染后就不会再变化,对应的DOM也不会变化。那么优化过程就是深度遍历AST树,按照相关条件对树节点进行标记。这些被标记的节点(静态节点)我们就可以跳过对它们的比对
,对运行时的模板起到很大的优化作用。
编译的最后一步是将优化后的AST树转换为可执行的代码
。
优点:
缺点:
Rerendering will not be performed immediately and synchronously. Vue's responsiveness does not mean that the DOM changes immediately after the data changes, but that the DOM is updated according to a certain strategy. Vue updates the DOM asynchronously. 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, in the next event loop tick, Vue flushes the queue and performs the actual (deduplicated) work.
Time complexity: The complete diff
algorithm of trees is a time complexity of
O(n*3), Vue optimizes and converts it into
O(n)
Understand:
Minimum update,
key is very important. This can be the unique identifier of this node, telling the
diff
Extension
v-for Why is there
key, without
key it will be violently reused, just give an example such as moving a node or adding a node (modifying DOM), adding
keyOptimization strategy of diff algorithm
: four hit searches, four pointers;
are simpler in data operation;
and realizes the encapsulation of
html And reuse, it has unique advantages in building single-page applications;
operations are very performance-intensive, and the native
dom operation nodes are no longer used, which greatly liberates
dom Operation, but the specific operation is still
dom but in another way;
, the same When operating virtual
dom, in terms of performance,
vue has great advantages.
Complete navigation parsing process:
调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。
简而言之,就是先转化成AST树,再得到的render函数返回VNode(Vue的虚拟DOM节点),详细步骤如下:
首先,通过compile编译器把template编译成AST语法树(abstract syntax tree 即 源代码的抽象语法结构的树状表现形式),compile是createCompiler的返回值,createCompiler是用以创建编译器的。另外compile还负责合并option。
然后,AST会经过generate(将AST语法树转化成render funtion字符串的过程)得到render函数,render的返回值是VNode,VNode是Vue的虚拟DOM节点,里面有(标签名、子节点、文本等等)
Vue 实现响应式并不是在数据发生后立即更新 DOM,使用 vm.$nextTick
是在下次 DOM 更新循环结束之后立即执行延迟回调。在修改数据之后使用,则可以在回调中获取更新后的 DOM。
什么时候被调用?
watch/event
事件回调。无 $el
. render
函数首次被调用vm.$el
替换,并挂载到实例上去之后调用改钩子。每个生命周期内部可以做什么?
ajax放在哪个生命周期?:一般放在 mounted
中,保证逻辑统一性,因为生命周期是同步执行的, ajax
是异步执行的。单数服务端渲染 ssr
同一放在 created
中,因为服务端渲染不支持 mounted
方法。 什么时候使用beforeDestroy?:当前页面使用 $on
,需要解绑事件。清楚定时器。解除事件绑定, scroll mousemove
。
受现代 JavaScript 的限制 ,Vue 无法检测到对象属性的添加或删除。由于 Vue 会在初始化实例时对属性执行 getter/setter 转化,所以属性必须在 data 对象上存在才能让 Vue 将它转换为响应式的。但是 Vue 提供了 Vue.set (object, propertyName, value) / vm.$set (object, propertyName, value)
来实现为对象添加响应式属性,那框架本身是如何实现的呢?
我们查看对应的 Vue 源码:vue/src/core/instance/index.js
export function set (target: Array<any> | Object, key: any, val: any): any { // target 为数组 if (Array.isArray(target) && isValidArrayIndex(key)) { // 修改数组的长度, 避免索引>数组长度导致splcie()执行有误 target.length = Math.max(target.length, key) // 利用数组的splice变异方法触发响应式 target.splice(key, 1, val) return val } // key 已经存在,直接修改属性值 if (key in target && !(key in Object.prototype)) { target[key] = val return val } const ob = (target: any).__ob__ // target 本身就不是响应式数据, 直接赋值 if (!ob) { target[key] = val return val } // 对属性进行响应式处理 defineReactive(ob.value, key, val) ob.dep.notify() return val }
我们阅读以上源码可知,vm.$set 的实现原理是:
The above is the detailed content of Sharing of Vue high-frequency interview questions in 2023 (with answer analysis). For more information, please follow other related articles on the PHP Chinese website!