30 Vue interview questions, including detailed explanations (ranging from beginner to proficient, self-test of Vue mastery)

preface

In this paper, from the perspective of the previous interviewers, some important features and principles of the Vue framework are sorted out and summarized in the form of questions, in order to help the authors and readers to measure their mastery of Vue.

1. Tell me your understanding of SPA single page. What are its advantages and disadvantages?

SPA (Single-Page Application) loads the corresponding HTML, JavaScript, and CSS only when the Web page is initialized. Once the page is loaded, SPA will not reload or jump the page because of the user’s operation. Instead, routing mechanisms are used to transform HTML content, interact with the user and avoid page reloading.

Advantages:

  • User experience is good, fast, content change does not need to reload the whole page, avoid unnecessary jump and repeated rendering;
  • Based on the above point, SPA exerts less pressure on the server.
  • The responsibilities of the front and back end are separated, and the architecture is clear. The front end carries out interactive logic, and the back end is responsible for data processing.

Disadvantages:

  • Time-consuming initial loading: To achieve single-page Web application functions and display effects, you need to load JavaScript and CSS in a unified manner. Some pages are loaded as required.
  • Forward and backward routing management: Because a single page application displays all content on a page, it cannot use the browser’s forward and backward function. All page switches need to build their own stack management.
  • SEO is difficult: because all content is displayed dynamically on a page, SEO has a natural disadvantage.

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

3, how to bind Class and Style dynamically?

Classes can be dynamically bound using object syntax and array syntax:

  • Object syntax:

    data: { isActive: true, hasError: false }

  • Array syntax:

    data: { activeClass: ‘active’, errorClass: ‘text-danger’ }

Style can also be dynamically bound with object syntax and array syntax:

  • Object syntax:

    data: { activeColor: ‘red’, fontSize: 30 }

  • Array syntax:

    data: { styleColor: { color: ‘red’ }, styleSize:{ fontSize:’23px’ } }

4. How to understand one-way data flow of Vue?

All prop forms a one-way downlink binding between their parent prop: updates to the parent prop flow down to the child, but not the other way around. This prevents accidental changes in the state of the parent component from the child, which can make the data flow of your application difficult to understand.

Additionally, every time the parent component is updated, all prop in the child component will be refreshed to the latest value. This means that you should not change a prop inside a child component. If you do, Vue will issue a warning in the browser console. If a child component wants to modify it, it can only send a custom event through $emit. If the parent component receives the custom event, the parent component can modify it.

There are two common situations when trying to change a prop:

  • This prop is used to pass an initial value; This child component next wants to use it as a local prop data. In this case, it is best to define a local data property and use this prop as its initial value:

    props: [‘initialCounter’], data: function () { return { counter: this.initialCounter } }

  • This prop is passed in as a raw value and needs to be converted. In this case, it is best to use the value of the prop to define a calculated property

    props: [‘size’], computed: { normalizedSize: function () { return this.size.trim().toLowerCase() } }

5. What are the differences between computed and Watch and the application scenarios?

Computed: Computed attributes depend on other attribute values, and computed values are cached. Only when the dependent attribute values change, computed values will be recalculated the next time it obtains computed values.

Watch: It is more of a function of “observation”, similar to the listening callback of some data. Whenever the monitored data changes, the callback will be executed for subsequent operations.

Application scenario:

  • When we need to do numerical calculations and rely on other data, we should use computed, because we can take advantage of the caching nature of computed and avoid recalculating each time we get a value.

  • Watch should be used when we need to perform asynchronous or expensive operations when data changes. Using the Watch option allows us to perform asynchronous operations (accessing an API), limits how often we perform that operation, and sets the intermediate state until we get the final result. These are all things you can’t do with computed properties.

6. Can Vue detect changes when assigning an array item directly?

Due to JavaScript limitations, Vue cannot detect the following array changes:

  • When you set an array item directly using an index, for example:vm.items[indexOfItem] = newValue
  • When you modify the length of an array, for example:vm.items.length = newLength

To solve the first problem, Vue provides the following operations:

Vue. Set Vue. Set (vm.items, indexOfItem, newValue) // Vue. $set(vm.items, indexOfItem, newValue) // array.prototype.splice vM. items. Splice (indexOfItem, 1, newValue)Copy the code

To solve the second problem, Vue provides the following operations:

// Array.prototype.splice
vm.items.splice(newLength)
Copy the code

7. What is your understanding of the Vue lifecycle?

(1) What is the life cycle?

A Vue instance has a full life cycle, that is, from the start of creation, initialization of data, compilation of templates, Dom mounting -> render, update -> render, uninstall, etc. We call this the life cycle of a Vue.

(2) The role of each life cycle

The life cycle

describe

beforeCreate

When a component instance is created, before its properties take effect

created

The component instance is fully created and the properties are bound, but the real DOM is not yet generated and $EL is not yet available

beforeMount

Called before the mount begins: The associated render function is called for the first time

mounted

El is replaced by the newly created vm.$el, which is called after being mounted to the instance

beforeUpdate

Called before component data is updated and occurs before the virtual DOM is patched

update

After the component data is updated

activited

Keep-alive is exclusive and is called when the component is activated

deactivated

Keep-alive is exclusive and is called when a component is destroyed

beforeDestory

Called before component destruction

destoryed

Called after component destruction

(3) Schematic diagram of life cycle

Vue parent component and child component lifecycle hook function execution sequence?

Vue’s parent and child component lifecycle hook function execution sequence can be categorized into the following four parts:

  • Loading the rendering process

    Parent beforeCreate -> Parent created -> parent beforeMount -> child beforeCreate -> child created -> child beforeMount -> Child Mounted -> parent Mounted

  • Child component update process

    Parent beforeUpdate -> Child beforeUpdate -> Child updated -> Parent updated

  • Parent component update process

    Parent beforeUpdate -> Parent updated

  • Destruction of the process

    Parent beforeDestroy -> Child beforeDestroy -> Child destroyed -> Parent destroyed

In which lifecycle is the asynchronous request invoked?

You can call hook functions created, beforeMount, and Mounted because in these three hook functions, data is already created and can be assigned to the data returned by the server. However, I recommend calling an asynchronous request from a Created hook function, because calling an asynchronous request from a Created hook function has the following advantages:

  • The server data can be obtained faster, reducing page loading time.
  • SSR does not support beforeMount and Mounted hook functions, so creating helps consistency.

At what stage can I access the manipulation DOM?

Before hook mounted is called, Vue has already mounted the compiled template to the page, so DOM can be accessed in Mounted. Vue life cycle diagram can be seen below, understand the operation of the entire life cycle phase, about the life cycle related interview questions are not difficult to you.

Can a parent component listen to the life cycle of a child component?

If the Parent component listens to the mounted component, then the Parent component does some logical processing.

// Parent.vue
<Child @mounted="doSomething"/>
    
// Child.vue
mounted() {
  this.$emit("mounted");
}
Copy the code

$emit triggers the parent component’s event manually. A simpler way is to use @hook to listen when the parent component references the child component, as shown below:

// Parent. Vue <Child @hook:mounted="doSomething" ></Child> doSomething() {console. '); }, // child.vue mounted(){console.log(' Child component raises mounted hook function... '); }, // The child component triggers the mounted hook function... // The parent listens to the mounted hook function...Copy the code

The @hook method not only listens for Mounted, but also for other lifecycle events, such as created, updated, etc.

12. What do you know about Keep-alive?

Keep-alive is a built-in component of Vue that can preserve the state of contained components and avoid re-rendering. It has the following features:

  • It is used together with routing and dynamic components to cache components.
  • Provide include and exclude attributes. Both of them support strings or regular expressions. Include indicates that only components with matching names will be cached, and exclude indicates that components with matching names will not be cached.
  • The hook function activated is activated when a component is activated, and the hook function deactivated is activated when a component is removed.

13. Why is data a function?

Why does data in a component have to be a function and then return an object, while data in a New Vue instance can be an object?

// data data() {return {message: "child component ", childName:this.name}} // new Vue new Vue({el: '#app', router, template: '<App/>', components: {App} })Copy the code

If data is an object in a component, then the scope is not isolated. The data property values in the subcomponent will affect each other. If the data option in a component is a function, then each instance can maintain an independent copy of the returned object. Data property values between component instances do not affect each other; The instance of new Vue is not reused, so there is no object reference problem.

14. How does v-Model work?

In the VUE project, we mainly used v-Model instructions to create two-way data binding on form input, Textarea, SELECT, etc. We knew that v-Model was essentially just syntax sugar. The V-Model internally uses different attributes for different input elements and throws different events:

  • Text and Textarea elements use value attributes and input events;
  • Checkbox and radio use the Checked attribute and the change event;
  • The SELECT field takes value as prop and change as an event.

Take the input form element for example:

<input V-model ='something'> equivalent to <input v-bind:value="something" V-on :input="something = $event.target.value">Copy the code

If in a custom component, the V-Model defaults to use a prop named Value and an event named input, as follows:

Parent: <ModelChild V-model ="message"></ModelChild> Child: <div>{{value}}</div> props:{value: String}, methods: {test1(){this.$emit('input', 'red ')},},Copy the code

15. What are the ways of communication between Vue components?

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.

16. Have you ever used Vuex?

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.

(1) The state storage of Vuex is responsive. When the Vue component reads the state from the Store, if the state in the store changes, the corresponding component is updated efficiently accordingly.

(2) The only way to change the state in a store is to explicitly commit mutation. This allows us to easily track each state change.

It mainly includes the following modules:

  • State: Data structure that defines the State of the application, where the default initial State can be set.
  • Getter: Allows the component to get data from the Store. The mapGetters helper function simply maps the getters in the Store to local computed properties.
  • Mutation: is the only method that changes the state in the store, and must be a synchronization function.
  • Action: Used to commit mutation rather than directly change the state, and can include any asynchronous operation.
  • Module: Allows you to split a single Store into multiple stores and Store them simultaneously in a single state tree.

17. Have you used Vue SSR? Tell me something about the SSR?

Vue.js is a framework for building client applications. By default, the Vue component can be exported to the browser for DOM generation and DOM manipulation. However, it is also possible to render the same component as server-side HTML strings, send them directly to the browser, and finally “activate” these static tags into a fully interactive application on the client side.

That is, SSR roughly means that vUE renders the entire HTML fragment of the label on the client side and completes the work on the server side. The HTML fragment formed by the server side is directly returned to the client side. This process is called server side rendering.

Advantages and disadvantages of server rendering SSR are as follows:

(1) Advantages of server-side rendering:

  • Better SEO: Because the content of SPA page is obtained through Ajax, and the search engine crawl tool does not wait for the completion of Ajax asynchronism before grabbing the page content, so the content of SPA page obtained through Ajax cannot be captured; SSR is directly returned by the server to the rendered page (data has been included in the page), so the search engine crawler can grab the rendered page;
  • Faster content arrival time (faster loading on the first screen) : SPA will wait for all Vue compiled JS files to be downloaded before rendering the page. File download takes a certain amount of time, so rendering on the first screen takes a certain amount of time. SSR directly returns the page rendered by the server directly, without waiting to download JS files and render again, so SSR has a faster content arrival time;

(2) Disadvantages of server-side rendering:

  • More development constraints: for example, server-side rendering only supports the beforCreate and Created hook functions, resulting in some external extension libraries requiring special handling to run in server-side rendering applications; And unlike fully static single-page application SPA, which can be deployed on any static file server, server-side rendering applications need to be in the Node.js server running environment;
  • More server load: Rendering a full application in Node.js is obviously more CPU-intensive than a server that only serves static files, so if you expect to use it in a high traffic environment, Prepare your server load and use caching strategies wisely.

If there is no SSR development experience of students, you can refer to the author of this article another SSR practice article “Vue SSR pit trip”, which SSR project construction and attached project source code.

18. How many vue-router routing modes are there?

Vue-router has three routing modes: hash, history, abstract. The corresponding source code is as follows:

switch (mode) { case 'history': this.history = new HTML5History(this, options.base) break case 'hash': this.history = new HashHistory(this, options.base, this.fallback) break case 'abstract': this.history = new AbstractHistory(this, options.base) break default: if (process.env.NODE_ENV ! == 'production') { assert(false, `invalid mode: ${mode}`) } }Copy the code

The three routing modes are described as follows:

  • Hash: Uses the URL hash value for routing. Support for all browsers, including those that don’t support the HTML5 History Api;

  • History: Relies on the HTML5 History API and server configuration. See the HTML5 History mode;

  • Support all JavaScript runtime environments, such as node.js server side. If the browser API is not found, routing automatically forces the mode into this mode.

19. Can you explain the hash and history routing modes used in vue-router?

(1) Implementation principle of hash mode

Early implementations of front-end routing were based on location.hash. The principle is simple: the value of location.hash is what comes after the # in the URL. For example, here’s a website whose location.hash value is ‘#search’ :

https://www.word.com#search
Copy the code

The hash routing mode is implemented based on the following features:

  • The hash value in the URL is only a state of the client, that is, when a request is made to the server, the hash part will not be sent.
  • Changes to the hash value add a record to the browser’s access history. So we can switch the hash through the browser’s back and forward buttons;
  • You can use the a tag and set the href attribute. When the user clicks on the tag, the HASH value of the URL will change. Or use JavaScript to assign loaction.hash to change the HASH value of the URL.
  • We can use the HashChange event to listen for changes in the hash value to jump (render) the page.

(2) The realization principle of history mode

HTML5 provides the History API to implement URL changes. The two main apis are history.pushstate () and history.repalcestate (). Both apis allow you to manipulate the browser’s history without refreshing it. The only difference is that the former is to add a history, while the latter is to replace the current history directly, as shown below:

window.history.pushState(null, null, path);
window.history.replaceState(null, null, path);
Copy the code

The history routing pattern is implemented based on the following features:

  • PushState and repalceState apis to implement URL changes;
  • We can use the PopState event to listen for URL changes to jump (render) the page;
  • History.pushstate () or history.replacEstate () will not trigger the popState event, so we need to trigger the page jump (rendering) manually.

20. What is MVVM?

Model — View — ViewModel (MVVM) is a software architecture design pattern developed by Ken Cooper and Ted Peters, Microsoft WPF and Silverlight architects, as an event-driven programming approach to simplifying user interfaces. Published by John Gossman (also WPF and Silverlight architect) on his blog in 2005

MVVM is derived from the classic Model-View-Controller (MVC) mode. The emergence of MVVM promotes the separation of front-end development and back-end business logic, greatly improving the efficiency of front-end development. The core of MVVM is the ViewModel layer. It is like a value Converter, responsible for transforming the data objects in the Model to make the data easier to manage and use. The layer has two-way data binding with the view layer up and data interaction with the Model layer down through interface requests. As shown below:

(1) View layer

A View is the View layer, the user interface. The front end is mostly built with HTML and CSS.

(2) Model layer

Model is an exponential data Model, which generally refers to various business logic processing and data manipulation carried out by the back end. For the front end, it is the API interface provided by the back end.

(3) ViewModel layer

A ViewModel is a layer of view data generated and maintained by an organization of front-end developers. In this layer, the front-end developer transforms and encapsulates the Model data from the back end to generate a View data Model that meets the expectations of the View layer. It should be noted that the data Model encapsulated by the ViewModel includes the state and behavior of the view, while the data Model of the Model layer only contains the state, such as what this piece of the page shows, what happens when the page loads in, what happens when you click this piece, What happens as this piece of scrolling is all part of the view behavior, the view state and behavior are encapsulated in the ViewModel. This encapsulation allows the ViewModel to fully describe the View layer.

The MVVM framework implements bidirectional binding, so that the contents of the ViewModel are displayed in real time in the View layer. Front-end developers no longer need to inefficiently and cumbersome manipulate the DOM to update the View. The MVVM framework already does the dirty and tiring work, and we developers only need to handle and maintain the ViewModel. Updating the data view automatically updates it accordingly. So the View layer doesn’t represent the data in the Model layer, it represents the data in the ViewModel layer, and the ViewModel is responsible for interacting with the Model layer. This completely decouples the View layer from the Model layer, and this decoupling is critical. It is an important part of the implementation of the front – end separation scheme.

We use a Vue example to illustrate the specific implementation of MVVM, students with Vue development experience should be clear at a glance:

(1) View layer

<div id="app">
    <p>{{message}}</p>
    <button v-on:click="showMessage()">Click me</button>
</div>
Copy the code

(2) ViewModel layer

Var app = new Vue({el: '#app', data: {// ',}, methods: {showMessage(){let vm = this; alert(vm.message); } }, created(){ let vm = this; Ajax ({url: '/your/server/data/ API ', success(res){vm.message = res; }}); }})Copy the code

(3) Model layer

{
    "url": "/your/server/data/api",
    "res": {
        "success": true,
        "name": "IoveC",
        "domain": "www.cnblogs.com"
    }
}
Copy the code

21. How does Vue implement bidirectional data binding?

Vue two-way data binding mainly refers to: data changes update view, view changes update data, as shown in the following figure:

That is:

  • When the content of the input box changes, the Data in Data changes synchronously. View => Data changes.
  • As the Data in Data changes, the content of the text node changes synchronously. Data => View changes.

Among them, View changes update Data, can be achieved through the way of event listening, so Vue two-way Data binding work is mainly how to update the View according to Data changes.

Vue implements bidirectional data binding through the following four steps:

Implement a listener Observer that iterates over data objects, including properties of child property objects, adding setters and getters to all properties using Object.defineProperty(). So, if you assign a value to this object, it will trigger the setter, so you can listen for changes in the data.

Implement a parser Compile: parse Vue template instructions, replace variables in the template with data, and then initialize render page view, and bind the corresponding node of each instruction to update function, add subscribers to listen to the data, once the data changes, receive notification, call update function for data update.

Implement a subscriber Watcher: The Watcher subscriber acts as a bridge between the Observer and Compile. Its main task is to subscribe to the message of the change of attribute value in the Observer. When the message of the change of attribute value is received, the corresponding update function in the parser Compile is triggered.

Implement a subscriber Dep: The subscriber uses a published-subscribe design pattern to collect subscriber Watcher and manage listener Observer and subscriber Watcher uniformly.

The flow chart of the above four steps is shown as follows. If you don’t understand it clearly, you can check the author’s article “0 to 1 Master: Vue Core Data Bidirectional binding”, with detailed explanation and code demo examples.

22. How does Vue implement object and array listening?

If you were asked how Vue implemented bidirectional data binding, you would probably answer that it hijacks data via Object.defineProperty(), but object.defineProperty () can only hijack attributes, not whole objects. Similarly, arrays cannot be hijacked, but we know from using the Vue framework that Vue can detect changes in objects and arrays (partial method operations). How does this work? We look at the relevant code as follows:

/** * Observe a list of Array items. */ observeArray (items: Array<any>) { for (let i = 0, l = items.length; i < l; I ++) {observe(items[I]) // Observe (items[I])}} /** * Recurse attributes */ let childOb =! Shallow && observe(val) // Observe changes in dataCopy the code

From the Vue source section above, we can see that the Vue framework is able to listen for objects and arrays (partial method operations) using Object.defineProperty() by iterating through groups of numbers and recursively traversing objects.

23. Comparison between Proxy and Object.defineProperty

Advantages of Proxy are as follows:

  • Proxies can listen directly on objects rather than properties;
  • Proxy can listen for array changes directly;
  • Proxy has up to 13 interception methods, not limited to apply, ownKeys, deleteProperty, has, etc. Object. DefineProperty does not have;
  • Proxy returns a new Object. We can only manipulate the new Object to achieve our purpose. Object.defineproperty can only be modified by iterating through Object attributes.
  • Proxy as the new standard will be subject to browser vendors focus on continuous performance optimization, which is the legendary performance bonus of the new standard;

Object.defineproperty has the following advantages:

  • It has good compatibility and supports IE9, but Proxy has browser compatibility problems and cannot be smoothed by Polyfill. Therefore, the author of Vue announced that Proxy can be rewritten until the next big version (3.0).

$set(); $set(); $set();

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 isArray if (array.isarray (target) &&isvalidarrayindex (key)) { Target.length = math.max (target.length, key) // Use the array splice method to trigger the response target.splice(key, 1). Val) return val} if (key in target &&! (key in Object.prototype)) { target[key] = val return val } const ob = (target: Any).__ob__ // Target itself is not a response data, directly assigned if (! Ob) {target[key] = val return val} 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)

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

26, Virtual DOM implementation principle?

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

27. What is the function of keys in Vue?

The key is a unique token for a Vnode in a Vue. With this key, our diff operation can be more accurate and faster. The DIff process of Vue can be summarized as follows: OldCh and newCh variables each have two end oldStartIndex, oldEndIndex and newStartIndex, newEndIndex, they will be old and new node node pairwise comparison, namely a total of 4 kinds of comparative way: NewStartIndex and oldStartIndex, newEndIndex and oldEndIndex, newStartIndex and oldEndIndex, newEndIndex and oldStartIndex, If none of the four comparisons match, if the key is set, the comparison will be performed using the key. During the comparison, the traversal will move towards the middle, and the comparison will end once StartIdx > EndIdx indicates that at least one of oldCh and newCh has been traversed. For specific diff process with or without key, you can check another detailed article about virtual DOM written by the author “In-depth Analysis: Virtual DOM at the core of Vue”.

Therefore, the function of key in Vue is: Key is the unique mark of Vnode in Vue. Through this key, our diff operation can be more accurate and faster

The sameNode function a. keey === B. Keey can be compared with the sameNode function a. keey === B. So it’s more accurate.

Faster: using the uniqueness of the key to generate map objects to obtain the corresponding nodes, faster than traversal, 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
}
Copy the code

28. What optimization did you make for 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

29. What do you know about the upcoming vue3.0 features?

Vue 3.0 is well on its way to release. The goal of Vue 3.0 is to make the Vue core smaller, faster, and more powerful, so Vue 3.0 adds these new features:

(1) Change of monitoring mechanism

3.0 will bring a proxy-based Observer implementation that provides reactive tracing with full language coverage. This removes many of the limitations of the object.defineProperty-based implementation in Vue 2:

  • Only properties can be monitored, not objects

  • Detect the addition and removal of attributes;

  • Detect array index and length changes;

  • Supports Map, Set, WeakMap, and WeakSet.

The new Observer also provides the following features:

  • A public API for creating Observables. This provides a simple and lightweight cross-component state management solution for small to medium scale scenarios.
  • Lazy observation is used by default. In 2.x, no matter how large the equation data is, it will be observed at startup. If your data set is large, this can cause significant overhead at startup time. In 3.x, only the data used to render the first visible part of the application is observed.
  • More accurate notification of changes. In 2.x, forcing a new attribute through vue.set causes the Watcher that depends on the object to be notified of the change. In 3.x, only the Watcher that depends on a particular property is notified.
  • Immutable Observable: We can create “immutable” versions of values (even nested properties) unless the system temporarily “unlocks” them internally. This mechanism can be used to freeze prop transfers or changes outside the Vuex state tree.
  • Better debugging: We can use new renderTracked and renderTriggered hooks to track exactly when and why components are being rerendered.

(2) Template

There were no major changes to the template, only the scope slots were changed. 2.x changed the scope slots and the parent component was re-rendered, while 3.0 changed the scope slots to function mode, which only affected the re-rendering of child components and improved rendering performance.

As for the render function aspect, vue3.0 will also make a number of changes to make it easier to use the API directly to generate the VDOM.

(3) Object-type component declaration

Components in vue2. X pass in a set of options declaratively, and TypeScript is combined with decorators, which are functional but cumbersome. 3.0 changes the way components are declared to be class-like, making it easy to integrate with TypeScript.

In addition, the source code for Vue is written in TypeScript. In fact, when the functionality of the code is complex, it is necessary to have a static type system to do some auxiliary management. Now vue3.0 is fully rewritten in TypeScript, making it easier for exposed apis to incorporate TypeScript. Static type systems are really necessary for the maintenance of complex code.

(4) Changes in other aspects

The changes to VUe3.0 are comprehensive, with only three major areas covered above, as well as some other changes:

  • Support for custom renderers, which allows WEEX to be extended by custom renderers instead of forking the source code.
  • Fragment (multiple root nodes) and Protal (rendering components in other parts of the DOM) components are supported for specific scenarios.
  • Based on Treeshaking optimization, more built-in features are provided.