This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

The introduction

This paper summarizes some important features and principles of Vue framework in the form of questions. The chapters are organized from easy to difficult, and readers are advised to read them in chapter order. It is hoped that after reading this article, readers will have some inspiration to think, and have a certain understanding of their mastery of Vue. They will make up for the omissions and have a better mastery of Vue.

The author will also stand in the perspective of the interviewer to answer the following questions, and appropriate analysis.

Why is data a function

The data in the component is written as a function, mainly to define the data in the form of the return value of the function. In this way, every time the component is reused, a new data will be returned, similar to creating a private data space for each component instance and letting each component instance maintain their own data.

If written purely in object form, all component instances share a copy of data, which will pollute a global variable.

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

All prop creates a one-way data flow between their parent prop: updates from the parent prop flow down to the child, but not the other way around. The main purpose of this is to prevent accidental changes in the state of the parent component from the child component, which may cause the application’s data flow to be difficult to understand.

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. The parent component can modify it after receiving the custom event.

What are the differences and application scenarios between 3.com Puted and Watch?

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. Otherwise, cached values will be obtained, saving performance.

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:

  • You should use computed when multiple value changes might affect a situation worth changing, because you can take advantage of the caching nature of computed and avoid recalculating each time a value is fetched.

For example, the current personnel database has birth date and entry date, but because age and length of service are dynamic, it is not suitable for database storage. In this case, computed cache can be used.

  • Watch should be used when it is worth changing a change that may affect multiple values,

For example, if a child component needs to listen to a value passed by the parent component, watch can be used to monitor the change of the child component’s own data.

4. Talk about your understanding of the life cycle

The 2.X version has a total of four phases in its lifecycle subdivided into eight hook functions

The four phases are the create phase, mount phase, update phase and destroy phase

BeforeMount (), Mounted (), beforeUpdate(), Update(), beforeDestroy(), destroyed().

According to the diagram of the life cycle on the official website, the execution sequence of VUE from top to bottom is

  • An instance object of Vue is created first

  • When executing the beforeCreated hook function, only some of the native properties and default events above this can be called when the life cycle is executed. The rest is not created yet.

  • When the created hook function is executed, the instance is created and the data in data or methods can be called. At this stage, the backend interface data is generally accessed with AXIOS for data processing.

  • Vue starts compiling the template, parses the tags in the template into the memory template string through h function, and then renders the template string into the virtual DOM through patch method. At this time, the template is only rendered in memory, without mounting the template to the real page

  • When executing beforeMount() hook function, this function is called when the template is already compiled in memory but not yet mounted to the page, so the page is old.

  • Update the virtual DOM to the browser page.

  • When the Mounted () hook function is executed, DOM node operations are performed.

  • The update phase is triggered by changes to data that exist in the template

  • When you execute the beforeUpdate() hook function, the data displayed in the page is still old, but the data in data is up to date, the page has not yet been synchronized with the data in data, and the state can be changed further without triggering duplicate rendering problems

  • First, according to the latest data in the data, render a latest memory DOM, when the latest memory DOM is updated, the latest memory DOM will be re-rendered to the latest page.

  • When the UPDATE () hook function is executed, the page and data are already in sync and all are up to date, so avoid changing the state or triggering the rendering problem repeatedly.

  • When executing the beforeDestroy() hook function, we can do some finishing work at this point, such as clearing the timer

  • Destroyed () removes all data and methods, filters, instructions, etc. All subinstances are destroyed as well.

5. Talk about your understanding of Vuex

Vuex is a mechanism to implement global state management of components and facilitate data sharing among components.

There are five attributes: Actions, state, getters, mutations and modules

State: This is a repository in which data is cached

Getters: this.$store. Getters: this.$store

Actions: are operated asynchronously, accessed through this.$store.dispatch

Mutations: Works simultaneously, accessed via this. codestore.mit

Modules: Modularity makes code cleaner

Use this. Codestore.mit to store values into State in a project, usually via the back-end data returned by AXIos

This $store. Getters values

Disadvantages: Because VUEX is a local cache, there will be data loss when the page is forced to refresh F5. Therefore, it is generally solved by cooperating with localStorage to make persistent storage or using sessionStorage for browser storage. However, too much data stored in localStorage will lead to page changes, because the nature of localStorage is to read the string, the specific use scheme still needs to be analyzed according to the specific project situation.

6. Talk about your understanding of the virtual DOM

Because DOM manipulation in the browser is very expensive, if using the real DOM directly, it will cause a large waste of performance, so the concept of virtual DOM is introduced. Using the virtual DOM, you can compare the difference between the virtual DOM and the real DOM, so as to achieve the purpose of optimizing performance by local rendering.

The processing of virtual DOM at the bottom of VUE is actually realized by referring to the open source library SNabbDOM. Specifically, a function is used to convert some tags in the template template into objects in the form of JS template string, and then the old and new virtual DOM are compared, so as to achieve the purpose of optimizing performance.

Advantages:

  1. No manual MANIPULATION of the DOM: We no longer need to manually manipulate the DOM, just write the code logic of the View-Model, and vUE will help update the View in a predictable way based on the virtual DOM and two-way data binding principles, greatly improving our development efficiency.
  2. Cross-platform: The virtual DOM is essentially a JavaScript object, and the DOM is platform-dependent, making cross-platform manipulation easier.

Disadvantages:

  1. 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.
  2. When the page initializes the DOM, the initial display is slower because of the extra layer of virtual DOM computation.

If you want an in-depth understanding of the virtual DOM, you can check out another article written by the author of this article, the Virtual DOM – Digging gold (juejin. Cn).

7. Talk about your understanding of the Diff algorithm

The bottom layer of VUE uses DIFF algorithm to compare old and new virtual DOM. The most important diFF algorithm is a patch method, in which sameVnode method is used to determine whether it is the same type of node, and patchVnode method is used to determine if it is the same type of node, and a deep comparison is made. The updateChildren method is used to compare the child nodes of the old and new virtual nodes. It mainly uses the head and tail pointer method for comparison. The matching sequence is as follows: before the new node compares the old one, after the new one compares the old one, after the new one compares the old one, after the new one compares the old one, after the new one compares the old one.

If you want to have an in-depth understanding of the DIFF algorithm, you can check out another article written by the author of this article [Vue in-depth].

8. Talk about your understanding of key 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.

If the key used to compare the old and new virtual Dom is not the same type of node, the entire node is directly replaced by the new virtual node.

If the key of the old and new virtual Dom is the same type of node, the deep comparison will continue. If the key is set, the comparison will be performed by key. During the comparison, the traversal will move towards the middle. The comparison ends once StartIdx > EndIdx indicates that at least one of oldCh and newCh has been traversed. Specific diff process with or without key.

If you want an in-depth understanding of the role of key, you can see the author of this article written another detailed explanation of the DIFF algorithm article [Vue in-depth] DIFF algorithm – Nuggets (juejin. Cn) there are Vue source code for the use of key judgment.

9. Talk about your understanding of Vue SSR

SSR is the rendering of a service, that is, the Vue tag rendered into HTML on the client work done on the server, and then put the HTML returned to the client directly, using SSR mainly to solve the problems of the first screen loading speed is slow, but he also has some disadvantages, it will also make our development conditions is restricted, Whether it is needed in the project or according to the specific requirements of the project to analyze and judge.

SSR advantages:

  • 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;

SSR faults:

  • 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;

10. Talk about your understanding of Vue bidirectional binding

Vue data bidirectional binding is implemented through data hijacking combined with the publicer-subscriber pattern. The principle is that the observer hijabs the getter setter for each property through object.defineProperty (), and the observer observes when the data changes. Watcher is notified of the data subscriber through Dep, and changes are made to the corresponding view.

Data hijacking:

Step 1: Perform recursive traversal of Observe’s data objects, including setters and getters for properties of child properties

So, if you assign a value to this object, it will trigger the setter, so you can listen for changes in the data

Step 2: Compile parses the template instruction, replaces the variables in the template with data, and initializes the render page view, binds the corresponding node of each instruction to update function, adds the subscriber that listens to the data, receives notification once the data changes, and updates the view

Step 3: The Watcher subscriber acts as a communication bridge between the Observer and Compile. It mainly does the following:

1. Add yourself to the attribute subscriber (DEP) during self instantiation

2. It must have an update() method

3. If you call your own update() method and trigger the callback bound with Compile, you are out of the game.

Step 4: MVVM, as the entry of data binding, integrates Observer, Compile and Watcher, uses Observer to monitor its model data changes, and uses Compile to parse and Compile template instructions. Finally, Watcher is used to build a communication bridge between Observer and Compile to achieve data change -> view update; View Interactive Changes (INPUT) -> Bidirectional binding effect of data model changes

11. Talk about your understanding of the Vue responsive principle

The vue2.X version of responsiveness relies on the underlying Object.defineProperty() and Object.definereActive () to form a closure environment that accesses getter and setter methods to respond

It is divided into object response type and array response type

Object responsive: In object responsitivity, data will be proxy or intercepted through observer to obtain getter and setter capabilities. Each attribute in data has a dependency on DEP, and each dependency is monitored by several Wachters. When the data in data changes, deP will be notified. The DEP informs Wachter, and Wachter takes the value from the corresponding data and renders it to the page.

Array responsiveness: Array_responder creates an arrayMthods based on array. prototype and then uses Object.setOrototypeOf to force our own arrays to point to arrayMthods, overriding the native methods of seven arrays (push, sort, Shfit, unshfit, pop, splice, reverse).

If an object is detected, the object response process will be carried out. However, there are some problems that cannot directly change the value of the corresponding index in the array. Therefore, this.

Vue introduces the concept of dependency collection by enabling views to be refreshed when a piece of data changes, and by synchronizing changes elsewhere that use the data.

12. Talk about your understanding of Vue’s reliance on collection

By iterating through all the attributes in data, add getter and setter to them using Object.defineProperty. In the getter, each attribute is recorded as a dependency by new Dep. Each dependency is monitored by several Wachters. Notify the corresponding DEP, which in turn informs Wachter, which takes the value from the corresponding data and renders it to the page.

Vue is executed asynchronously when updating the DOM. As long as it listens for data changes, Vue opens a queue and buffers all data changes that occur in the same event loop. If the same watcher is triggered more than once, it will only be pushed into the queue once. This removal of duplicate data while buffering is important to avoid unnecessary computation and DOM manipulation.

$nextTick this.$nextTick

Since vUE has a dependency collection mechanism, if a value of data is changed, it is not immediately reflected in the page. Instead, a queue is opened and all data changes in the same event loop are buffered. Queue tasks are executed only when the current task is idle, which has a latency.

When $nextTick is executed, it is an asynchronous event, and it will queue this event. Asynchronous events are code that will not be executed immediately. They will be queued by the JS handler and executed one by one according to the order and priority of the queue. So, when the first modification to data is rendered after the page, $nextTick is executed, and you’re sure to get the DOM stuff.

The this.$nextTick() method is mainly used in dom applications where data changes. Data and DOM rendering are asynchronous in vUE, so any dom structure changes with data should be placed in the callback function of this.$nextTick()

Tell me about a cross-domain problem you solved

The cause is that the front end and the back end of the server url is inconsistent.

Generally speaking, if the front-end server is 3000 and the back-end server is 5000, a cross-domain error will occur. The front-end will send the request header data to the back-end, and the back-end will send the response data back to the front-end, but the response data will be intercepted by the Ajax engine, so a cross-domain error will occur.

Typically we use proxies to solve cross-domain problems.

The principle of using proxies to cross domains is to send the domain name to the local server (start the vUE project service, Loclahost :8080), and then the local server requests the real server.

There are two main ways to configure proxies in VUE

1. Configure the proxy to only want back-end servers in package.json file (rarely used)

2. Perform the configuration in the vue.config.js file in the vue root directory (common)

Configure target, changOrigin and pathRewrite

The target parameter points to the real interface in the background

The changOrigin parameter is set to true to allow cross-domain

The pathRewrite parameter overwrites the path

15. Talk about any improvements you have made to the Vue project

  • Don’t make the object hierarchy too deep, or performance will be poor (Object.defineProperty will traverse listening)

  • Do not put reactive data in data (Object.defineProperty enables listening for every attribute of the object)

  • V-if and V-show are used in different scenarios

  • Computed and Watch distinguish usage scenarios

  • V-for traversal must include a key, preferably an ID value, and do not use v-if at the same time

  • Big data list and table performance optimization – virtual list

  • Big Data drop-down component performance optimization – Lazy data loading

  • To prevent internal leaks, destroy global variables and events after component destruction

  • Route lazy loading

  • On-demand introduction of third-party plugins (not all of them, or the package will be too bulky)

  • Use the keep-alive cache component as appropriate

  • Anti – shake, throttling application

  • Server rendering SSR

recommended

If you want to continue learning about browsers, you can watch another article by me on juejin.

If you want to continue to learn the principles of CSS, you can watch the author of another article (interview treasure guide) CSS chapter – Nuggets (juejin. Cn)

If you want to continue to learn the JS principle of readers, you can watch the author of another article [interview treasure guide] high frequency front end questions of JavaScript principle – nuggets (juejin. Cn)

If there are readers who want to continue to learn the common method of handwriting JS, you can watch the author of another article [interview treasure guide] high frequency front end questions of handwriting commonly used JS method – digging gold (juejin. Cn)

conclusion

This article is the author’s personal study notes, if there are fallacies, please inform, thank you! If this article has been helpful to you, please click the “like” button. Your support is my motivation to keep updating.