Home > Web Front-end > Vue.js > body text

Sharing of Vue high-frequency interview questions in 2023 (with answer analysis)

青灯夜游
Release: 2022-12-15 20:04:35
forward
4147 people have browsed it

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.

Sharing of Vue high-frequency interview questions in 2023 (with answer analysis)

What are the Vue-router navigation guards?

  • Global prefix/hook: beforeEach, beforeResolve, afterEach
  • Routing exclusive guards: beforeEnter
  • Guards within the component: beforeRouteEnter, beforeRouteUpdate, beforeRouteLeave

(Learning video sharing: vue video tutorial )

Why is Proxy adopted in Vue3.0 and Object.defineProperty abandoned?

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();
Copy after login

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.

v-for Why add key

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

How to go from real DOM to virtual DOM

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

Why does Vue use asynchronous rendering?

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).

Why does data in the vue component have to be a function?

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.

The difference between MVC and MVVM

MVC

MVC’s full name is Model View Controller, which is model-view (view) - the abbreviation of controller, a software design model

  • Model (model): It is the part of the application that is used to process the application data logic. Usually the model object is responsible for accessing data in the database
  • View (View): It is the part of the application that handles data display. Usually the view is created based on the model data
  • Controller (controller): It is the part of the application that handles user interaction. Usually the controller is responsible for reading data from the view, controlling user input, and sending data to the 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

  • ViewModel 层:做了两件事达到了数据的双向绑定 一是将【模型】转化成【视图】,即将后端传递的数据转化成所看到的页面。实现的方式是:数据绑定。二是将【视图】转化成【模型】,即将所看到的页面转化成后端的数据。实现的方式是:DOM 事件监听。

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。

Vue 为什么要用 vm.$set() 解决对象新增属性不能响应的问题 ?你能说说如下代码的实现原理么?

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
}
Copy after login
Copy after login

我们阅读以上源码可知,vm.$set 的实现原理是:

  • 如果目标是数组,直接使用数组的 splice 方法触发相应式;

  • 如果目标是对象,会先判读属性是否存在、对象是否是响应式,

  • 最终如果要对属性进行响应式处理,则是通过调用 defineReactive 方法进行响应式处理

defineReactive 方法就是 Vue 在初始化对象时,给对象属性采用 Object.defineProperty 动态添加 getter 和 setter 的功能所调用的方法

Vue3.0 和 2.0 的响应式原理区别

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, // 当修改属性时调用此方法
};
Copy after login

Vue模版编译原理知道吗,能简单说一下吗?

简单说,Vue的编译过程就是将template转化为render函数的过程。会经历以下阶段:

  • 生成AST树
  • 优化
  • codegen

首先解析模版,生成AST语法树(一种用JavaScript对象的形式来描述整个模板)。 使用大量的正则表达式对模板进行解析,遇到标签、文本的时候都会执行对应的钩子进行相关处理。

Vue的数据是响应式的,但其实模板中并不是所有的数据都是响应式的。有一些数据首次渲染后就不会再变化,对应的DOM也不会变化。那么优化过程就是深度遍历AST树,按照相关条件对树节点进行标记。这些被标记的节点(静态节点)我们就可以跳过对它们的比对,对运行时的模板起到很大的优化作用。

编译的最后一步是将优化后的AST树转换为可执行的代码

MVVM的优缺点?

优点:

  • 分离视图(View)和模型(Model),降低代码耦合,提⾼视图或者逻辑的重⽤性: ⽐如视图(View)可以独⽴于Model变化和修改,⼀个ViewModel可以绑定不同的"View"上,当View变化的时候Model不可以不变,当Model变化的时候View也可以不变。你可以把⼀些视图逻辑放在⼀个ViewModel⾥⾯,让很多view重⽤这段视图逻辑
  • 提⾼可测试性: ViewModel的存在可以帮助开发者更好地编写测试代码
  • ⾃动更新dom: 利⽤双向绑定,数据更新后视图⾃动更新,让开发者从繁琐的⼿动dom中解放

缺点:

  • Bugs are difficult to debug: Because of the two-way binding mode, when you see an exception in the interface, there may be a bug in your View code, or there may be a problem in the Model code. Data binding allows bugs in one location to be quickly transferred to other locations, making it not easy to locate the original problem location. In addition, the declaration of data binding is written imperatively in the View template, and these contents cannot be interrupted and debugged
  • The model in a large module will also be very large, even if it is used It is convenient to use and it is easy to ensure the consistency of data. If it is held for a long time, more memory will be consumed if the memory is not released.
  • For large graphics applications, the view state is relatively small. If there are many, the cost of building and maintaining ViewModel will be relatively high.

After the value of a property in Vue data changes, will the view be re-rendered synchronously immediately?

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.

diff algorithm

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

    algorithm that they are the same DOM node before and after the change
    • Extensionv-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 key
    • will only move less Manipulate the DOM.
  • Only the same virtual node will be compared in detail, otherwise the old one will be violently deleted and the new one will be inserted.
  • Only comparisons will be made within the same layer, and no cross-layer comparisons will be made.

Optimization strategy of diff algorithm

: four hit searches, four pointers
  1. Old before and new before (compare the beginning first, then insert and deletion of nodes)
  2. Old after and new after (ratio of end, before insertion or deletion)
  3. Old before and new after (ratio of head and tail, this happens If a moving node is involved, then the node pointed to by the new front will be moved to the end of the old one. Node, before moving to the old one)
---If you can all understand the above questions, you are basically O---

The following simple concepts, You must have no problem?

Advantages of Vue

    Lightweight framework: It only focuses on the view layer, which is a collection of views that builds data. The size is only a few dozen
  • kb;
  • Simple and easy to learn: developed by Chinese, Chinese documents, no language barriers, easy to understand and learn;
  • Two-way data binding: retained The characteristics of
  • angular are simpler in data operation;
  • Componentization: retains the advantages of
  • react and realizes the encapsulation of html And reuse, it has unique advantages in building single-page applications;
  • Separation of views, data, and structures: making data changes simpler, without modifying the logic code, only needing to operate the data. Related operations;
  • Virtual DOM:
  • dom 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;
  • runs faster: compared to
  • react, the same When operating virtual dom, in terms of performance, vue has great advantages.

vue-router What is the routing hook function and what is the execution order?

The execution process of the routing hook. The types of hook functions are: global guard, routing guard, Component Guard

Complete navigation parsing process:

  • Navigation is triggered.

  • Call the beforeRouteLeave guard in the deactivated component.

  • Call the global beforeEach guard.

  • Call the beforeRouteUpdate guard (2.2) in the reused component.

  • Call beforeEnter in routing configuration.

  • Resolve asynchronous routing components.

  • Call beforeRouteEnter in the activated component.

  • Call the global beforeResolve guard (2.5).

  • Navigation confirmed.

  • Call the global afterEach hook.

  • Trigger DOM update.

  • 调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。

Vue.js的template编译

简而言之,就是先转化成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节点,里面有(标签名、子节点、文本等等)

$nextTick 是什么?

Vue 实现响应式并不是在数据发生后立即更新 DOM,使用 vm.$nextTick 是在下次 DOM 更新循环结束之后立即执行延迟回调。在修改数据之后使用,则可以在回调中获取更新后的 DOM

说说Vue的生命周期吧

什么时候被调用?

  • beforeCreate :实例初始化之后,数据观测之前调用
  • created:实例创建万之后调用。实例完成:数据观测、属性和方法的运算、 watch/event 事件回调。无 $el .
  • beforeMount:在挂载之前调用,相关 render 函数首次被调用
  • mounted:了被新创建的vm.$el替换,并挂载到实例上去之后调用改钩子。
  • beforeUpdate:数据更新前调用,发生在虚拟DOM重新渲染和打补丁,在这之后会调用改钩子。
  • updated:由于数据更改导致的虚拟DOM重新渲染和打补丁,在这之后会调用改钩子。
  • beforeDestroy:实例销毁前调用,实例仍然可用。
  • destroyed:实例销毁之后调用,调用后,Vue实例指示的所有东西都会解绑,所有事件监听器和所有子实例都会被移除

每个生命周期内部可以做什么?

  • created:实例已经创建完成,因为他是最早触发的,所以可以进行一些数据、资源的请求。
  • mounted:实例已经挂载完成,可以进行一些DOM操作。
  • beforeUpdate:可以在这个钩子中进一步的更改状态,不会触发重渲染。
  • updated:可以执行依赖于DOM的操作,但是要避免更改状态,可能会导致更新无线循环。
  • destroyed:可以执行一些优化操作,清空计时器,解除绑定事件。

ajax放在哪个生命周期?:一般放在 mounted 中,保证逻辑统一性,因为生命周期是同步执行的, ajax 是异步执行的。单数服务端渲染 ssr 同一放在 created 中,因为服务端渲染不支持 mounted 方法。 什么时候使用beforeDestroy?:当前页面使用 $on ,需要解绑事件。清楚定时器。解除事件绑定, scroll mousemove

Vue 怎么用 vm.$set() 解决对象新增属性不能响应的问题 ?

受现代 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
}
Copy after login
Copy after login

我们阅读以上源码可知,vm.$set 的实现原理是:

  • 如果目标是数组,直接使用数组的 splice 方法触发相应式;
  • 如果目标是对象,会先判读属性是否存在、对象是否是响应式,最终如果要对属性进行响应式处理,则是通过调用 defineReactive 方法进行响应式处理( defineReactive 方法就是 Vue 在初始化对象时,给对象属性采用 Object.defineProperty 动态添加 getter 和 setter 的功能所调用的方法)

(学习视频分享:web前端开发编程基础视频

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template