Vue must meet questions + answers

Vue video tutorial series:

Tencent Vue actual combat questionnaire website video tutorial

Full tutorial contents: Click to view

The latest Vue+Spring travel project

Full tutorial contents: Click to view

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

Full tutorial contents: Click to view

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

Full tutorial contents: Click to view

Vue mobile terminal e-business project based on VantUI

Full tutorial contents: Click to view

Why doesn’t Vue have a life cycle similar to shouldComponentUpdate in React?

Vue changes detection principle

Pre-knowledge: dependency collection, virtual DOM, responsive systems

The root cause is that Vue and React detect changes differently

React detects changes in pull mode. When React knows about changes, it uses the Virtual Dom Diff difference detection, but a lot of components are actually definitely not changing, this time need to use shouldComponentUpdate manual operation to reduce Diff, so as to improve the overall performance of the program.

Vue detects changes in pull+push mode. It knows from the start that the component has changed, so it doesn’t need to manually control the DIFF during the push phase. The diFF mode used inside the component can actually introduce a shouldComponentUpdate related lifecycle, but usually Components of a reasonable size do not have excessive diff, and manual optimization is of limited value, so for now Vue is not considering introducing shouldComponentUpdate as a manual optimization lifecycle.

What exactly does a key in Vue do?

The key is the unique ID marked for the Vnode in the Vue, and with this key we can make diff operations more accurate and faster

In the process of diFF algorithm, the beginning and end of the new node will be compared with the end of the old node. When there is no match, the key of the new node will be compared with the old node, and then the difference will be exceeded.

The diff procedure can be summarized as follows: oldCh and newCh each have two starting and ending variables, StartIdx and EndIdx. Their two variables are compared with each other, and there are altogether four ways of comparison. If none of the four comparisons match, if the key is set, the comparison will be made with the key, and during the comparison, the variable will move towards the middle, and the comparison will end as soon as StartIdx>EndIdx indicates that at least one of oldCh and newCh has been traversed. The four comparisons are head, tail, old tail, new head, old head, new head.

  • Accuracy: if not addedkey, then VUE will choose to reuse the node (VUE’s in-place update strategy), resulting in the state of the previous node being preserved, which will cause a series of bugs.
  • Fast: The uniqueness of the key can be fully utilized by the Map data structure. The time complexity of the Map is only O(1) compared to the time complexity of the traversal search O(n).

Vue vs. React

=> Similarity:

2. Both have virtual DOM, component-based development, and use props parameter to transfer data between parent and child components, which implements the webComponents specification 3. React has react Native, vue has WexxCopy the code

=> Differences:

1. Data binding: Vue implements two-way data binding, react data flows are one-way 2. 3. Usage scenarios: React and Redux architecture are suitable for large-scale multi-person collaboration complex projects, while Vue is suitable for small and fast projects 4. React Recommended approach JSX + inline style puts HTML and CSS in js. Vue uses webpack + VUE-loader single file component format, HTML, JS, CSS in one fileCopy the code

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.

Talk about the Vue lifecycle

When is it called?

  • BeforeCreate: called after instance initialization and before data observation
  • Created: called after the instance is created. Instance completion: data observation, property and method operations, watch/eventEvent callback. There is no $el .
  • BeforeMount: Called before mounting, related renderThe function is called for the first time
  • Mounted: Specifies whether a vm is newly createdvm.$elReplace, and mount to the instance after the change hook is called.
  • BeforeUpdate: Called before data update, occurs after the virtual DOM is re-rendered and patched, after which the change hook is called.
  • Updated: Virtual DOM rerender and patch due to data changes, after which the change hook is called.
  • BeforeDestroy: Called before instance destruction, the instance is still available.
  • Destroyed: Called after the instance is destroyed. After called, everything indicated by the Vue instance is unbound and all event listeners and all subinstances are removed

What can be done inside each life cycle?

  • Created: The instance is already created, and since it is the first created instance, some data and resource requests can be made.
  • Mounted: The INSTANCE is mounted. DOM operations can be performed on the instance.
  • BeforeUpdate: State can be further changed in this hook without triggering rerendering.
  • Updated: It is ok to perform DOM-dependent operations, but avoid changing the state, which may cause an update wireless loop.
  • Destroyed: Performs optimization actions, clears timers, and unbinds events.

Which lifecycle does Ajax fall into? In Mounted to ensure logical consistency, because the lifecycle is executed synchronously and Ajax is executed asynchronously. Singular server rendering SSR is also included in created because server rendering does not support Mounted. When to use beforeDestroy? : The current page uses $on and needs to be unbound. Know the timer. Unbind the event, scroll Mousemove.

Have you ever written a custom instruction how does it work

Directives are essentially decorators that are vUE extensions to HTML elements, adding custom capabilities to HTML elements. When VUE compiles the DOM, it finds the instruction object and executes the methods associated with the instruction.

A custom directive has five lifecycles (also called hook functions), namely bind, INSERTED, Update, componentUpdated, and unbind

1. Bind: Called only once, when the directive is first bound to an element. This is where you can perform one-time initialization Settings. 2.inserted: Called when the bound element is inserted into a parent (the parent is guaranteed to exist, but not necessarily already inserted). Update: Called when the template to which the element is bound is updated, regardless of whether the binding value changes. Unnecessary template updates can be ignored by comparing the binding values before and after the update. 4. ComponentUpdated: Called when the template to which the bound element belongs completes an update cycle. 5. Unbind: Called only once, when an instruction is unbound from an element.Copy the code

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.

Vue uses vm.$set() to respond to new attributes.

Restricted by modern JavaScript, Vue cannot detect the addition or deletion of object attributes. Since Vue performs getter/setter conversions on the property when it initializes the instance, the property must exist on the data object for Vue to convert it to reactive. $set (object, propertyName, value)/vm.$set (object, propertyName, value)/Vue.

We view the corresponding Vue source: 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

  • If the target is an array, use the array splice method directly to trigger the corresponding expression.
  • If the target is an object, the presence of the attribute and whether the object is reactive are first read. Finally, if the attribute is to be processed responsively, it is processed responsively by calling the defineReactive method (the defineReactive method is when Vue initializes the object, Method called to dynamically add getters and setters to Object properties using Object.defineProperty)

Pros and cons of the virtual DOM?

Advantages:

  • Lower performance: The framework’s virtual DOM needs to accommodate any operations that the upper-level API may produce, and some of its DOM operations must be implemented in a universal way, so its performance is not optimal; But performance is much better than rough DOM manipulation, so the framework’s virtual DOM can at least guarantee decent performance without having to manually optimize it.
  • No need to manually manipulate the DOM: We no longer need to manually manipulate the DOM, just need to write the code logic of the View-Model, the framework will help us update the View in a predictable way according to the virtual DOM and data two-way binding, greatly improving our development efficiency;
  • Cross-platform: The virtual DOM is essentially a JavaScript object, and the DOM is platform-dependent. In contrast, the virtual DOM can be more easily cross-platform, such as server rendering, WEEX development, and so on.

Disadvantages:

  • Extreme optimization cannot be carried out: Although reasonable optimization of virtual DOM + is sufficient to meet the performance requirements of most applications, targeted extreme optimization cannot be carried out in some applications with extremely high performance requirements.

How does the virtual DOM work?

The realization principle of virtual DOM mainly includes the following three parts:

  • JavaScript objects are used to simulate the real DOM tree and abstract the real DOM.
  • Diff algorithm — Compare the difference between two virtual DOM trees;
  • Pach algorithm – The difference between two virtual DOM objects is applied to a real DOM tree.

If you are not familiar with the above three parts, you can check out another detailed explanation of virtual DOM written by the author of this article, “In-depth Analysis: Virtual DOM at the heart of Vue”.

What optimizations have you made to the Vue project?

If you have not summarized the optimization of THE Vue project, you can refer to another article “Vue Project Performance Optimization – Practical Guide” written by the author of this article. The article mainly introduces how to optimize the Vue project in detail from three major aspects and 22 small aspects.

(1) Optimization at the code level

  • V-if and V-show are used in different scenarios
  • Computed and Watch distinguish usage scenarios
  • V-for traversal must add a key to the item and avoid using v-if at the same time
  • Long list performance optimization
  • Destruction of events
  • Lazy loading of image resources
  • Route lazy loading
  • The introduction of third-party plug-ins on demand
  • Optimize infinite list performance
  • Server render SSR or prerender

(2) Optimization of Webpack level

  • Webpack compresses images
  • Reduce redundant code from ES6 to ES5
  • Extract common code
  • Template precompilation
  • Extract the COMPONENT’s CSS
  • Optimize SourceMap
  • Build results output analysis
  • Compilation optimization of Vue project

(3) Optimization of basic Web technology

  • Enable Gzip compression
  • Browser cache
  • The use of CDN
  • Use Chrome Performance to find Performance bottlenecks