This video I think he will be good is to directly go to the analysis of vue source code, from the source analysis, simple and easy to understand and persuasive.

Conclusion: a total of 9 sections and 9 small knowledge points

1, V-IF and V-for comparison 2, VUE component data function form 3, key function 4, DIFF algorithm 5, componentization 6, VUE design concept 7, MVC MVP and MVVM 8, VUE optimization 9, VUe3 features

1. V-if and V-for have a higher priority. If they appear at the same time, how can we optimize them for better performance

V-for is resolved before V-if

After the guidance of the comments section, the conclusion is changed to:

2. X When v-if and V-for are used together, v-for has a higher priority than V-if.

3. X When v-if and V-for are used together, v-if has a higher priority than V-for.Note: – l: is a function of the list of rendering the return is the end result, check the vue source: path to the SRC/compiler/codegen/index. The js fileIt is found in the source code to handle static nodes first (staticRoot) and then to handle once and finally to handle for code to show that for takes precedence over if breakpoint debugging is also confirmed for takes precedence over if conclusion:1, V-for is parsed before V-if (tell the interviewer how you know, read the source code) 2. If it happens at the same time, each render will execute a loop to determine the condition first, which is inevitable anyway, wasting performance 3. To avoid this, nest the template in the outer layer, do the V-if judgment in this layer, and then do the V-for loop inside

2. Why must the Vue component data be a function when the vue root instance is not?

Conclusions: 1. Data must be a function to ensure that in the case of multiple instances, in order to protect the states between each other without interference and pollution. 2, each time when creating the root instance, use new method, global scope only create one, do not create multiple, there is no pollution problem, so can not use the function

The function returns a new data object instance each time it executes

The test code is as follows:

Data initialization is in: the SRC/core/instance/init. Js fileFocus on the initData function in the study source found:At line 116, a judgment is made on data, executed if data is of type function. Vue.com Ponent’s comp property is actually executed only once in the above test case column, that is, when the second parameter is processed, it is processed only once. The data option points to the same place. Different instances of a component actually use the same data, resulting in data contamination. If it is a component, the data in the component cannot be set as in the test

When creating the root instance each time, use the new method, the global scope only creates one, does not create multiple, there is no pollution problem, so can not use the function,

In the case of multiple instances, to protect the states between each other without interference, without pollution. The root instance of vue therefore needs to use the function function

Conclusion:

A VUE component may have multiple instances. If you define data using objects, they will share a single data object. State changes will affect all component instances, which is not reasonable. In the vue root instance creation process, there is no change restriction, because there can only be one root instance, do not need to worry about this problem

3. How key works and explain your understanding of it

SRC /core/vdom/ patch.js-updatechildren ()

It is more efficient to perform the diff algorithm by uniquely identifying a DOM element

If you update it 3 times without the key and you insert it once with the key and you insert it once

Conclusion:

1. Key is mainly used to update virtual DOM efficiently. The principle is that vUE can accurately judge whether two nodes are the same by key during patch, so as to avoid frequent updates of different elements, make the whole patch process more efficient, reduce the amount of DOM operation and improve performance

2, if you do not set the key may cause some hidden bugs when the list is updated, such as the update and not update can not be seen.

3. Vue also uses the key attribute when transitioning elements with the same label name. The purpose is also to allow VUE to distinguish between them, otherwise VUE will only replace its internal attributes without triggering the transition effect. You need a key as a measure of uniqueness.

4. How to understand the DIff algorithm in VUE

Summary: DIFF algorithm: not vUE in the special, all involved in the virtual DOM have diFF algorithm necessity: DIFF algorithm can accurately compare the new and old virtual DOM key changes, so as to improve the update efficiency execution mode: depth first, peer comparison efficiency: view the source code:

1. Necessity of DIFF algorithm:

/ / Mounted is invoked when a vUE component instance is created. / / Mounted is invoked when a component instance is created. / / Mounted is invoked when a vUE component instance is created.

Conclusion: There are multiple data keys in the component, how to ensure that the key changes, perform the diff algorithm can compare the old and new two virtual DOM comparison, in order to know exactly

2. The execution mode of diFF algorithm

Core source: line 586 startingAnalysis: patchVnode is where diff occurs, and the overall strategy is:Depth first, same layer comparisonFirst, compare the root node to see if there are children. If so, update the child node to compare the child node to the bottom layer. Specific code If it finds a direct update child node, if it doesn’t see another operation,

3. Efficiency of DIFF algorithm:

That’s updateChildern () that I mentioned above

Conclusion: 1. Diff algorithm is the inevitable product of virtual DOM technology: The old and new virtual DOM are compared (i.e., DIFF) to update the changes on the real DOM. In addition, the efficient execution of the comparison process by DIFF is also required to reduce the time complexity to O (n) 2. In Vue2.0x, in order to reduce the granularity of watcher, each component only has one Watcher corresponding to it. 3. The moment of DIff execution in VUE is when the component instance executes the update function, it will compare with the last rendering result oldVnode and the new rendering result. This process is called patch 4. Comparison between the two nodes according to whether they have child nodes or text node do different operations, compared two groups of child nodes is a key, the algorithm first hypothesis head nodes could be done 4 times same contrast to try, if not found the same node to be carried out in accordance with the general way to traverse the search, search over again according to the situation to deal with the rest of the nodes, With the help of key, the same node can be found very accurately, so the whole patch process is very efficient.

5. Understanding of VUE componentization

General answer idea: componentization definition, advantages, use scenarios and matters needing attention and so on. At the same time, some characteristics of VUE componentization should be emphasized

1. Source code analysis: component definition

I’m going to separate out some of the individual functions, separate functions, so I can reuse the common definitions in VUE the first one is the global definition and the second one is the single file component definitionSource: the SRC/global/assets. Js /

2, source code analysis: componentization advantages

Lifecycle. Js-mountcomponent () Maintainability testability, reusability, from component Watcher, rendering function to analyze the execution component, each component will correspond to a Watcher, component and changes will only when the inside of the calling component rendering functions, often change data alone can put a component, the late only need to perform this function, Play the role of local refresh.

3. Realization of componentization

Constructor: SRC /core/global-api/extend.js instantiate and mount: SRC /core/vdom, patch.js-createelm ()Conclusion 1. Components areAn independent and reusable unit of code organization. Component system is one of the core features of VUE, which enables developers to build large applications using small, independent and usually reusable components. 2. Componentized development can greatly improve application development efficiency, testability, reusability, etc. 3. 4. Vue components are configuration based, we usually write components that are component configurations rather than components, the framework will then generate its constructors, which are based on vueComponent. 5. Common componentization technologies in VUE include: Attribute prop Custom events. Slot, they are mainly used for component communication, expansion, etc. 6, reasonable division of components, help improve the performance of the application 7. Components should be highly cohesive and low coupled 8. Follow the principle of one-way data flow

6. Understanding of VUE design principles

Vue is an incremental JavScript framework that is easy to use, efficient and flexible

Answer progressive javascript frameworks based on these two points:

Unlike other large frameworks, VUE is designed to be applied layer by layer from the bottom up. Vue’s core library, which focuses only on the view layer, is not only easy to get started with, but also easy to integrate with existing projects of third-party libraries, on the other hand, when used in combination with modern toolchains and various supporting libraries. Vue also completely can provide driving core library for complex single page is some statement yes rendering, component system Only focus on the view layer can be used as a library to use in other projects, also can be used as to set up the framework of a large project, this is gradual Learning is a gradual process, learning only template syntax, basis functions can be developed, I learned engineering later,

Ease of use:

Vue provides core features such as data responsiveness, declarative template syntax, and configuration-based component systems that allow us to focus only on the core business of the application, as long as we can write JS. HTML and CSS make it easy to write vUE applications

Flexibility:

Progressive framework biggest advantage is flexibility, if the application is small enough, we may need the vue core features alone will go to completion, with the expansion of the scale, we can only was chasing the introduction of routing, state management, vue – cli libraries and tools, such as whether the application volume or learning difficulty is a gradually increasing gentle curve

Efficiency:

The super-fast virtual DOM and DIff algorithms give our applications the best performance, and the quest for greater efficiency continues. The introduction of proxy responsiveness to data in VUe3 and improvements to static content in the compiler make VUE even more efficient

7. Understanding of MVC MVP and MVVM

Answer:

There are a lot of knowledge points involved, and it is difficult to explain them clearly, because we front-end programmers have not used MVC MVp models themselves. At that time, it just reflects the change process from nothing to something and from something to excellence in these years

“Age

There was no front-end in web1.0. ASP.NET, Java PHP projects usually have multiple aspx/ JSP/HPH single file to compose, each file has HTML CSS js or Java code

In order to make the development more convenient, the code is easy to maintain, the responsibility of the front and back end is clear, MVC development pattern and framework. A typical framework in the form of a front-end presentation template is Spring Structs Hibernate (SSH)The goal is to layer data, view and business logic control for easy maintenance and reading and writing. The front end only completes the View layer in the back end but still puts all the code logic in the server side. There are problems: 1, the front end page development efficiency is not high; 2, the front end responsibilities are not clear

Web2.0 era

Ajax technology has been around since Gmail came along. The responsibilities of the front and back end are clearer, because the front end can interact with the back end through Ajax, so the overall architecture diagram is changed to:The front end only needs to develop the page content. The data is provided by the background, and the project can realize Ajax to make the page partially refresh, reducing the server side load and traffic consumption, a lot of rendering from the server side to the client side, and some library jquery has been developed in the front end

The problem: There is no viable development model to accommodate more complex business requirements, and the page content is all mixed up, which becomes difficult to maintain once the application scale increases, hence the MVC on the front end

Architecture evolution for back-end separation: MVC MVP MVVMMVC The FRONT-END MVC is similar to the back-end, with View, Controller and Model Model: responsible for saving application data. Contoller: in charge of service logic and modify Model data according to user behaviors. View: in charge of View display. Visualize the data in the model:It works in theory, but it’s not convenient in practice, and then it evolves (this is still MVC)Such a pattern may also bring some problems: 1. Data flow chaosAs shown in the figure, the view is relatively large, while the Controller is relatively simple. As many developers will write some logical code in the view, the content in the view will gradually become bigger and bigger, while the controller becomes thinner and thinner, and the changes of the front end seem to lack the MVP mode. Angular skipped MVP by putting MVVM mode in the front end early

MVP MVP is very close to MVC. P refers to Persenter’s understanding as a middleman, who is responsible for the data flow between the View and the Model, preventing the view from communicating directly with the emodel,P is responsible for bidirectional interaction with M and V, and the view becomes a passive view, which is very small and separates V and M. However, the application becomes very large, which leads to the increase in the volume of P and makes it difficult to maintain.

MVVM The core of MVVM is the vm layer in the middle: the ViewModel automatically responds to data changes in the Model by implementing a set of data-dependent mechanisms. At the same time, the ViewModel will implement a set of update side rates that automatically convert data changes to View updates by responding to user interaction in the View to modify data in the Model through time monitoring. This reduces the amount of DOM manipulation code in the ViewModel. MVVM keeps the View and Model loosely coupled while reducing the amount of code needed to maintain their relationship, using the user to focus on the business logic and keeping development rates and maintainability in mind

Conclusion: 1. These three are framework patterns, and their design goal is to solve the coupling problem of Model and View. 2. MVP mode in the MVC evolution form, Presenter as the middle layer responsible for MV communication, to solve the coupling problem, but the P layer in the past oversize will lead to maintenance problems. 4. MVVM mode is widely used in the front-end field, it not only solves the MV coupling problem, It also solves the complex code and DOM manipulation required to maintain the projective relationship between the two, which means that there is no need to change the DOM manipulation one by one, while improving development efficiency and readability while maintaining superior performance

8. What performance optimization methods do you know about VUE

The optimization of VUE level is mainly discussed

1. Route lazy loading:

2. Keep-alive cache page

3. Reuse DOM using V-show

4, V-for traversal avoid using v-if simultaneously

Evaluate attributes to filter the array ahead of time

5. Long list performance optimization

If the list is purely a display of data and doesn’t change the data you don’t need to be reactiveFreeze using the Freeze method, or change the property to false

For large data lists, you can use virtual scrolling to render only a small portion of the areaSee Third-party Components.

6. Event destruction

When a VUE component is destroyed, all instructions and event listeners are automatically unbound, but only for the component’s own events

7. Lazy loading of images

For pages with too many pictures, in order to accelerate the loading speed of the page, we often need to load the pictures that do not appear in the visual area of the page, and wait until the scroll to the visual area to load

8. Import third-party plug-ins as required

Third-party component libraries such as Element-UI can be mapped on demand to avoid oversizeUse the bable plugin

Stateless components are marked as functional components

Display component, so there is no instance tag functional

10. Sub-component segmentation

Some of the more time-consuming sub-components are separated into a component, do their own rendering, not affecting the other components

11. Localization of variables

Reault is actually a property computed and a property of base which is time-consuming,

12 、SSR

Server rendering.

9 New features of VUe3.0

Faster:

Virtual DOM rewriting optimizes slots to generate static trees to promote static attributes to promote proxy-based responsive systems

Smaller:

By tree shaking optimization core library volume static nodes are marked out to reduce rewriting

Easier to maintain:

The TypeScript + modular

Be friendlier:

Cross-platform: Compiler core and runtime core are platform independent, making vUE easier to use with any platform (Web Android IOS)

Easier to use:

Improved TypeScript support, powerful type checking and error and warning editing, better debugging, and support for the independent reactive module CompositionAPI

Several directions are highlighted: virtual DOM rewriting looks forward to more compile-time hints to reduce runtime overhead, making it easier to optimize the JS engine by making efficient code to create virtual node components faster + a single call + child node type detection to skip unnecessary conditional branches

Optimized Slots generates separate re-renders of parent and child components in VUe3 to ensure that instances track dependencies correctly and avoid unnecessary re-renders of parent and child components

In case of staticTree promotion, means that vue3’s compiler will be able to detect what is static and then apply it as a reactor. as a result, the rendering cost will be reduced

Static attribute promotion Using static attribute promotion, vue3 patch will skip these attributes will not change the node children need to continue to change

Proxy-based data responsive Vue2.0 uses Object. DefinfPropertyde Getter and setter vue3 will use ES6 proxies as an observation mechanism: Component instance initialization speed up to 100% using Proxy to save the previous half of the memory is too small to love fast speed, but there is low browser version incompatibility, in order to continue to support IE11 vue3 will be released on the observer mechanism and a new Proxy version build

Highly maintainable VUE3 will lead to more maintainable source code that not only uses Typescript but also many packages that are decoupled and more modular

Today is the last day of National Day, I have been silent for a long time, and I have to start studying seriously recently. I haven’t written a blog and taken notes for more than three months. Recently, I have started a new plan and prepared to write a new series. Mainly vUE some underlying principles and algorithms. Autumn recruitment has come to an end, now it is stable, continue to study and prepare for spring recruitment, it must be great to see the students here, the road of learning is difficult, but the rare time means that you are going uphill, come on, you will live as you want!!