Vue principle (1)


Componentization and MVVM


Traditional components are only static rendering, and update depends on DOM operation.
Data driven view——Vue MVVM。 Pay more attention to data and business logic.


ModelData →ViewView →Controllercontroller
MVVM —— Model View ViewModel, data, view, view model
modelcorrespondingdata,viewcorrespondingtemplate,vmcorrespondingnew Vue({…})
The relationship between the threeviewIt can be done throughEvent bindingHow to influencemodelmodelIt can be done throughData bindingThe form ofviewviewModelIt’s amodelandviewConnected connector.
Vue principle (1)

MVVMThree elements of framework

  • Response formula:VueHow to monitordataEach attribute change of
  • Template engine:VueHow are templates parsed and instructions processed
  • Rendering:VueHow is the template renderedhtmlWhat is the rendering process like


Responsive: once the data of component data changes, the view will be updated immediately. The data attribute is proxied to the VM.
The first step in implementing a data-driven view.


Core API for monitoring data changes

Object.definedProperty Basic Usage
It can directly define a new property on an object, or modify an existing property of an object and return the object. vue.js This method is formally used to realize the bidirectional binding of data, so as to achieve the purpose of responsive.adopt Object.definedProperty Listen to get and set of object properties

Object.defineProperty(obj, prop, descriptor)

Object: the object on which to add or modify properties.
Propertyname: a string containing the name of the property. They are the properties and methods that need to be defined.
Descriptor: can contain the following attributes. By default, writable, enumerable, and configurable values are false
There are also two methods (two-way data binding takes advantage of these two methods, namely accessor) get () and set ()

Accessors set and get
Set(); this method is called automatically once the property is reassigned.
Get(); this method is called automatically once the property is accessed and read.

let data = {};
let name = 'zhangsan';
Object.defineProperty(data, "name", {
    get: function () {
    set: function (newVal) {
        name = newVal;

// undefined = "list";//set

vue.js Data hijacking combined with publisher subscriber mode is adopted Object.defineProperty () to hijack the setters and getters of each property, and release messages to subscribers when the data changes, triggering the corresponding monitoring callback.

Object.definedProperty Several shortcomings of

Deep monitoring requires recursion to the end, which requires a large amount of one-time calculation.
Unable to listen for new / deleted properties.
Unable to listen to array natively. Special handling is required.

Vdom and vdiff

Vdom is an important cornerstone of Vue. Diff algorithm is the core and key part of vdom.

Vdom (virtual DOM)

With our traditional development mode, when operating DOM with native JS or JQ, the browser will execute the process from beginning to end from building DOM tree.
The cost of DOM operation is expensive. Frequent operation will cause page jam, which will affect the user experience. Therefore, it is proposed that:

Use js to simulate DOM structure, calculate the minimum change, and operate dom

If the DOM is updated 10 times in one operation, the virtual DOM will not operate the DOM immediately, but save the diff contents of these 10 updates to a local JS object. Finally, the JS object will be attched to the DOM tree at one time, and then subsequent operations will be carried out to avoid a large amount of unnecessary calculation.
The real meaning of vdom is to achieve cross platform, server-side rendering and provide a DOM update strategy with good performance.

Rendering virtual DOM to a real DOM actually takes a lot of experienceVNodeThe definition ofdiffpatchEtc


Virtual DOM usesVNodethisClassTo describe,

Core attributes of vnode

  • tagAttribute is the label attribute of this vnode
  • dataThe attribute contains the class, attribute, style and bound events on the node after it is finally rendered to a real DOM node
  • childrenAttribute is a child of vnode
  • textProperty is a text property
  • elmAttribute is the real DOM node corresponding to this vnode
  • keyAttribute is the token of vnode, which can improve the efficiency of diff

Algorithm implementation

1. UseJSObject simulationDOMTrees**

<div id="div1" class="container">
    <ul style="font-size: 20px">
            children: [

2. Compare the difference between two virtual DOM trees diff algorithm**

diffThe algorithm is used to compare two treesVirtual DOMIf a complete comparison of two trees is required, thendiffThe time complexity of the algorithm isO(n^3)。 But in the front end, you rarely move across levelsDOMElement, soVirtual DOMOnly elements at the same level are compareddivIt’s only at the same leveldivCompared with the second level, the second level will only be compared with the second level, so that the algorithm complexity can be achievedO(n)
Vue principle (1)

There are four cases of horizontal diff
Node replacement: the node is changed, for example, the div above is replaced by H1;
For example, change the order of adding and deleting sub nodes;
Attribute change: modify the attribute of the node, for example, delete the class style class of Li above;
Text change: change the text content of the text node, for example, change the text content of the above P node to “real DOM”;

Difference objects (patches): we can get what changes have been made between the two virtual DOM objects through the difference object, so as to change the original real DOM structure according to the difference objects (patches), so as to change the DOM structure of the page.


Mainly by callingpatchVnodeMethods

diffThere are several situations in the process,oldChbyoldVnodeThe child node of,chbyVnodeChildren of:

  • First of all, if the text is judgedoldVnode.text !== vnode.textThen the text node will be replaced directly;
  • stayvnodeIf there is no text node, enter thediff
  • WhenoldChandchCall theupdateChildrenOn the child nodediff
  • ifoldChnon-existent,chExist, empty firstoldVnodeAt the same timeaddVnodesMethods willchAdd toelmrealdomAmong nodes;
  • ifoldChExistence,chIf it does not exist, it will be deletedelmUnder the real nodeoldChSub node;
  • ifoldVnodeThere are text nodes, andvnodeNo, clear the text node.
Child nodediffProcess analysis

Why must a unique key be added when using V-for?
Vue principle (1)
We hope to add an F between B and C. the default implementation of diff algorithm is as follows:
Vue principle (1)
Is it inefficient to update C to F, D to C, e to D, and finally to insert e?
So we need to use the key to give each node a unique identification, diff algorithm can correctly identify this node, find the correct location area and insert a new node.
Vue principle (1)
So,Key is used to update virtual DOM efficiently.

3. Make two virtualDOMObject differences apply to realDOMTrees**

Recommended Today

PHP 12th week function learning record

sha1() effect sha1()Function to evaluate the value of a stringSHA-1Hash. usage sha1(string,raw) case <?php $str = “Hello”; echo sha1($str); ?> result f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0 sha1_file() effect sha1_file()Function calculation fileSHA-1Hash. usage sha1_file(file,raw) case <?php $filename = “test.txt”; $sha1file = sha1_file($filename); echo $sha1file; ?> result aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d similar_text() effect similar_text()Function to calculate the similarity between two strings. usage similar_text(string1,string2,percent) case […]