Front-end VUE interview questions, with answers

Vue video tutorial series:

Tencent Vue actual combat questionnaire website video tutorial

Video tutorial: Click to see

Full tutorial contents: Click to view

The latest Vue+Spring travel project

Video tutorial: Click to see

Full tutorial contents: Click to view

Vue3.0 (official version) + TS Imitation Zhihu column enterprise-level project

Video tutorial: Click to see

Full tutorial contents: Click to view

Vue3.0+TS to build an enterprise component library front-end required for senior developers

Video tutorial: Click to see

Full tutorial contents: Click to view

Vue mobile terminal e-business project based on VantUI

Video tutorial: Click to see

Full tutorial contents: Click to view

What design patterns are used in VUE

1. Factory mode – Create instance by passing in parameters

The virtual DOM returns the Vnode of the base tag and the component Vnode depending on the parameter

2. Singleton mode – There is only one instance of the entire program

The vuex and VUE-Router plug-in registration method install determines if there is an instance of the system directly return to the system

3. Publish-subscribe (VUE event mechanism)

4. Observer mode (Responsive data Principle)

5. Decorator mode: (@ decorator usage)

A policy pattern is when an object has a behavior that can be implemented differently in different scenarios – for example, a merge strategy of options

Do you know the principle of Vue template compilation? Can you explain it briefly?

To put it simply, Vue compilation is the process of converting a template into a render function. Will go through the following stages:

  • Generate the AST tree
  • To optimize the
  • codegen

The template is first parsed to generate an AST syntax tree (a form of JavaScript object that describes the entire template). A large number of regular expressions are used to parse templates, and the corresponding hooks are used to process tags and texts.

Vue data is responsive, but not all data in the template is. Some data doesn’t change after the first rendering, and the corresponding DOM doesn’t change either. Then the optimization process is to deeply traverse the AST tree and mark tree nodes according to relevant conditions. The tagged nodes (static nodes) can then be skipped over to optimize the run-time template.

The final step in compilation is to convert the optimized AST tree into executable code.

Template compilation of vue.js

The render function returns VNode (Vue’s virtual DOM node).

First, compile the template into an AST syntax tree using the Compile compiler. Compile is the return value of createCompiler. CreateCompiler is used to create compilers. Compile is also responsible for merging options.

The AST then generates the render function by generating (converting the AST syntax tree into a render funtion string). The render returns VNode, which is a Vue virtual DOM node containing (tag name, child nodes, text, etc.)

Know anything about nextTick?

Asynchronous methods, the last step in asynchronous rendering, are closely associated with THE JS event loop. Using macro tasks and microtasks (setTimeout, Promise, etc.), we defined an asynchronous method that would queue the method multiple calls to nextTick and clear the current queue asynchronously.

The implementation principle of computed

Computed in nature is an lazily evaluated observer.

Computed implements an inert WATcher internally, that is,computed Watcher, which does not evaluate immediately and holds an instance of DEP.

The this.dirty attribute tag internally calculates whether the attribute needs to be reevaluated.

When computed dependency status changes, the lazy Watcher is notified,

Computed Watcher detects subscribers by this.dep.subs.length,

If it does, it recalculates and compares the old and new values, and if it changes, it rerenders. (Vue wanted to make sure that not only did the values of the calculated property dependencies change, but that the rendering Watcher was only triggered to re-render when the final calculated value of the calculated property changed, essentially an optimization.)

If not, just set this.dirty = true. (When a calculated property depends on other data, it is not recalculated immediately, but only computed later when the property needs to be read elsewhere, which is called lazy.)

Why does Vue use vm.$set() to solve the problem that new object attributes cannot respond? Can you explain how the following code works?

$set() = Vue = Vue; $set() = Vue = Vue

  1. Vue uses Object.defineProperty for two-way data binding
  2. Perform getter/setter conversions on properties when initializing instances
  3. A property must exist on a data object for Vue to convert it to responsive (which makes it impossible for Vue to detect the addition or deletion of an object property)

$set (object, propertyName, value)/vm.$set (object, propertyName, value)

2) How is the framework itself implemented?

Vue source location: Vue/SRC/core/instance/index. Js

export function set (target: Array<any> | Object, key: any, val: any) :any {
  // Target is an array
  if (Array.isArray(target) && isValidArrayIndex(key)) {
    // Change the length of the array to avoid index > array length errors caused by splcie()
    target.length = Math.max(target.length, key)
    // Use the array splice mutation method to trigger the response
    target.splice(key, 1, val)
    return val
  }
  // The key already exists
  if (key intarget && ! (keyin Object.prototype)) {
    target[key] = val
    return val
  }
  const ob = (target: any).__ob__
  // Target itself is not reactive data, directly assigned
  if(! ob) { target[key] = valreturn val
  }
  // Respond to attributes
  defineReactive(ob.value, key, val)
  ob.dep.notify()
  return val
}
Copy the code

$set vm.$set vm.$set

  1. If the target is an array, use the array splice method directly to trigger the corresponding expression.
  2. If the target is an object, it first checks whether the property exists and whether the object is reactive.
  3. Finally, if you want to do reactive processing for attributes, you do it by calling the defineReactive method

DefineReactive is what Vue calls when it initializes an Object and dynamically adds getters and setters to Object properties using Object.defineProperty

What’s the difference between V-show and V-IF?

V-if is true conditional rendering because it ensures that event listeners and subcomponents within the conditional block are properly destroyed and rebuilt during the switch; Also lazy: if the condition is false during the initial render, nothing is done — the conditional block does not start rendering until the condition is true for the first time.

V-show is much simpler — elements are always rendered regardless of initial conditions, and simply switch based on the “display” property of CSS.

Therefore, V-IF is suitable for scenarios where conditions are rarely changed at runtime and do not need to be switched frequently; V-show is suitable for scenarios that require very frequent switching of conditions.

How can Vue components communicate with each other?

Communication between Vue components is one of the knowledge points often tested in the interview. This question is similar to the open question. The more methods you answer, of course, the more bonus points, indicating that you are more proficient in Vue. Vue component communication refers only to the following three types of communication: parent-child component communication, intergenerational component communication, and sibling component communication. We will introduce each of these communication modes and explain which types of component communication this method can be applied to.

(1)props / $emitApplicable to parent-child component communication

This method is the basis of the Vue component, and I believe most of you have heard of it, so I will not introduce it here with examples.

(2)ref$parent / $childrenApplicable to parent-child component communication

  • refIf used on a normal DOM element, the reference refers to the DOM element. If used on a child component, the reference refers to the component instance
  • $parent / $children: Accesses the parent/child instance

(3)EventBus ($emit / $ON)It is suitable for communication between father-child, intergenerational, and sibling components

This approach uses an empty Vue instance as the central event bus (event hub), which triggers events and listens for events to communicate between any component, including parent, generational, and sibling components.

(4)$attrs/$listenersIt is suitable for intergenerational component communication

  • $attrs: contains property bindings (except class and style) in the parent scope that are not recognized (and retrieved) by prop. When a component does not declare any prop, all parent-scoped bindings (except class and style) are included and can passv-bind="$attrs"Pass in internal components. Often used in conjunction with the inheritAttrs option.
  • $listeners: contains a V-ON event listener in the parent scope (without the.native modifier). It can go throughv-on="$listeners"Passing in internal components

(5)provide / injectIt is suitable for intergenerational component communication

The ancestor component provides variables through provider, and the descendant component injects variables through Inject. Provide/Inject API mainly solves the communication problem between cross-level components, but its usage scenario is mainly that sub-components obtain the state of the upper level components, and a relationship between active provision and dependency injection is established between cross-level components.

(6) Vuex is suitable for father-son, intergenerational and sibling component communication

Vuex is a state management mode developed specifically for vue.js applications. At the heart of every Vuex application is the Store. A “store” is basically a container that contains most of the states in your app.

  • Vuex’s state storage is reactive. When the Vue component reads the state from the Store, if the state in the store changes, the corresponding component is updated efficiently accordingly.
  • The only way to change the state in a store is to commit mutation explicitly. This allows us to easily track each state change.

What exactly does a key in Vue do?

The key is the unique ID given to each vNode, with which our diff operations can be more accurate and faster (diff nodes are also faster for simple list page rendering, but with hidden side effects such as not having transitions, or binding data (form) state on some nodes, State mismatches can occur.)

In the process of diFF algorithm, the beginning and end of the new node will be compared with the old node. When there is no match, the key of the new node will be compared with the old node, so as to find the corresponding old node.

The sameNode function a. keey === B. Keey can be compared with the sameNode function a. keey === B. Therefore, it will be more accurate. If you do not add key, the state of the previous node will be retained, which will cause a series of bugs.

Faster: The uniqueness of the key can be fully exploited by the Map data structure, and the Map’s time complexity is only O(1) compared to the time complexity of traversal lookup O(n).