preface

  • Comparison of the three front-end frameworks
The framework Year published from Number of star features
Angular In 2010, Google 73.7 k. Two-way data binding
React In 2013, Facebook 169k VirtualDOM, Redux
Vue In 2014, Especially the rain creek EvanYou 184k More lightweight, easy to use, Chinese document friendly
  • Framework convergence/mutual learning

    • Vue borrowed from the Knockout template engine, Angular two-way data binding, and React virtual DOM/Redux /JSX
    • Cross-end Development (Ionic/ReactNative/Weex)
    • Desktop Development (Electron supports VUE/React)
    • In a word, you have I have all have, everyone is really good
  • Vue-like development mode (new track) : mini program, UniApp

After reading this article, you will know:

  • What is Vue? What problem was solved?
  • The MVVM architecture
  • Three elements (responsive, template compilation, VDOM/DIFF algorithm)
  • Component rendering/update process

PS: This article mainly focuses on Vue2 and involves a small amount of VUe3.0 content

What is Vue?

What is vue?

Vue (pronounced vju/curliest, similar to View) is a set of progressive frameworks for building user interfaces. Unlike other large frameworks, Vue is designed to be applied layer by layer from the bottom up. Vue’s core library focuses only on the view layer, making it easy to get started and integrate with third-party libraries or existing projects. On the other hand, when combined with modern toolchains and various supporting libraries, Vue is perfectly capable of providing drivers for complex, single-page applications.

  • Lightweight incremental framework (easy to integrate with third-party libraries or existing projects)
  • Rich ecology (VUE-CLI, VUE-Router, VUex, community UI component library…)
  • Easy to get started (easy to get started and friendly to Chinese documents)

What problem does VUE solve?

  • HTML: from 0 to 1
  • CSS: Provides decoration
  • JavaScript(DOM) : Supports dynamic pages (such as countdown)
  • JQuery: Browser Compatibility issues, elegant API
  • Vue: Data-driven view that frees developers from DOM manipulation (e.g. countdown, autoadder)

Question: How does data-driven view work? (Data changes -> View updates)

1. How to understand MVVM

MVVM is a software architecture pattern. MVVM is a variant of THE MVP pattern. Both the MVP pattern and MVVM pattern are variants of the MVC pattern. MVC, MVP, and MVVM diagrams

The software architecture decouples the code and layers do not affect each other, which effectively reduces the development complexity. We can achieve architectural goals by adjusting the previous communication patterns of MVC and MVC.

The impact of MVVM on view update mode

  • Static rendering: Updates require DOM manipulation, such as ASP/JSP/PHP, suitable for simple business scenarios
  • Data-driven views: Views that can be updated with data, such as Vue/React/Angular, are suitable for complex business scenarios

MVVM consists of three parts:

  • View: The user sees the structure, layout, and appearance of a screen. Also called UI
  • ViewModel: is a binder, can andViewModelLayer to communicate
  • Model: Data and logic

2. Embodiment of MVVM in Vue

Example:

<template>
    <div id="app">
      <h1>{{ message }}</h1>
      <button @click="reverse">reverse</button>
    </div>
</template
Copy the code
var app = new Vue({
    el: "#app".data: {
      message: "Hello Vue123!!"
    },
    methods: {
      reverse() {
        this.message = this.message.split("").reverse().join(""); }}});Copy the code
  • View: the template template
  • Model: the data of the data
  • The ViewModel: Vue instance

PS: Vue does not strictly follow the MVVM pattern: Strict MVVM rules require that the View cannot communicate directly with the Model, and Vue violates this rule by providing the $refs attribute in the component to allow the Model to manipulate the View directly.

Question: How does VUE implement MVVM?

3. Vue three elements

  • Reactive: How does vUE listen for every property change in data?
  • Template engine: How are vue templates parsed?
  • Render: How does Vue render efficiently?

Two, Vue three elements – response type

Reactive: Changes in the component data immediately trigger an update to the view.

How is responsiveness implemented?

Object. DefineProperty (ie 9 +)

let obj = {};
let value = null;
Object.defineProperty(obj, 'a', {
    get: () = > {
        console.log('trigger get');
        // Collection depends on todo...
        return value;
    },
    set: (val) = > {
        console.log('trigger set');
        if(val ! == value) { value = val;// Data change, need to re-render todo...}}})console.log(obj.a);
obj.a = 1;
Copy the code

disadvantages

  • Deep monitoring needs to recurse to the end, which requires a large amount of one-time calculation
  • Unable to listen for new/deleted attributes (Vue.$set)
  • Unable to native listen array, requires special handling

Proxy (Vue3.0, IE11+)

let obj = {}
let reactiveObj = new Proxy(obj, {
    get: function(obj, prop) {
        console.log('trigger get');
        // Collection depends on todo...
        return obj[prop];
    },
    set: function(obj, prop, value) {
        console.log('trigger set');
        obj[prop] = value;
        if(obj[prop] ! == value) {// Data change, need to re-render todo...}}})Copy the code

Disadvantages:

  • There are compatibility issues with caniuse 95%
  • It modifies the way some of the underlying JavaScript code is executed, so it can’t be completely polyfilled

Problems with responsiveness:

  • JQuery can control the timing of DOM manipulation manually, while responsive DOM manipulation takes place internally.
  • DOM manipulation is very performance-intensive

Question: How do I effectively control DOM manipulation?

Three elements of Vue – Rendering: Virtual DOM (Virtual DOM)

Vue is a data-driven view. How can you effectively control DOM manipulation?

  • Solution:vdom
    • JS execution speed is fast
    • Use JS to simulate the DOM structure, calculate the smallest changes, and manipulate DOM
  • vdomIt is an optimal solution, not a responsive necessity
    • vdomIs to realize thevuereactAn important cornerstone of
    • The diff algorithmvdomThe most central and critical part of
  • Simulate DOM structure with JS:vnode
<div id="div1" class="container">
    <p>vdom</p>
    <ul style="font-size: 20px;">
        <li>a</li>
    </ul>
</div>
Copy the code
{
    tag: 'div'.props: {
        classname: 'container'.id: 'div1'
    },
    children: [{tag: 'p'.children: 'vdom'
        },
        {
            tag: 'ul'.props: { style: 'font-size: 20px; ' },
            children: [{tag: 'li'.children: 'a'}]}]}Copy the code
  • vdomSummary: Effectively control DOM manipulation in data-driven view mode
    • vnode: Use JS to simulate the DOM structure
    • The diff algorithm: Compares the old and new vNodes, obtains the minimum update range, and finally updates the DOM

Diff algorithm – VDOM core part

Diff algorithm is an efficient algorithm that compares nodes in the tree of the same layer, avoiding layer by layer search traversal of the tree, so the time complexity is only O(n).

Summary:

  • Diff is contrast and is a broad (not original) concept, such as the Linux diff command, git diff, etc
  • Two JS objects can also do diff
  • Two trees do diff, like vDOM diff here

Time complexity O(n^3) for Tree Diff

  • Tree1; tree2; 3
  • 1000 nodes, 100 million computations, algorithm is not available

Optimization time complexity to O(n)

  • Compare only the same level, not across levels
  • If the tag is different, delete it and rebuild it
  • Tag and key, both identical, are considered the same node, update the DOM, and continue to compare the node’s children

Diff algorithm flow

1. For the first rendering, take vNode for rendering

2. After data update, compare vNode with oldVnode

  • Start from the root node to traverse, determine whether the current old node and the new node are the same node (same SEL and key)
  • If the node is not the same, delete it and rebuild it.
  • If the node is the same, the dom of the current node is updated, continuing with the children element

Add 4 Pointers to point to the beginning and end of the comparison of the old and new children respectively, and close the loop from both sides to the middle;

  • Step 1: start start, end end, start end and end start are compared respectively. If the match is successful, the pointer is closed to the middle.
  • Step 2: If the first step is not matched, traverse the old children to find whether the starting node of the new children is matched. If the match is successful, move the old node to the corresponding position.
  • Step 3: After the loop, add or delete nodes according to the number of old and new nodes

Each scene diagram (see animation here 👉 Diff algorithm graphic animation)

Remove nodes

The new node

Not set the key

Set the key

It should be noted that there are three types of overhead for updating a node:

  • The first is to rebuild the node and update the DOM when the node cannot be reused
  • The second is to update the DOM directly when the node can be reused
  • The third is the ability to reuse nodes, but move the DOM and then update it

The third case is an array with a key.

Five, Vue three elements – template compilation

  • An overview of
    • Preknowledge: JS with syntax
      • Change the lookups for free variables in {} as obj attributes
      • If no matching obj attribute is found, an error is reported
      • Use with with with. It breaks scope rules and makes it less readable
    • What exactly are Vue templates (not HTML, with instructions, interpolation, JS expressions)?
    • How does Vue handle templates? Component rendering and update process?
  • Steps:
    1. Vue – the template – the complier will template<template>Compile into the render function
    2. Execute the render function to generate a VNode
    3. Patch and diff are performed based on VNode to render and update
    4. After data is modified, a new VNode is generated
  • What the Vue template is compiled into (vue-template-compiler

<p>{{message}}</p>

with(this){return _c('p', [_v(_s(message))])}

Similar to:

render: function (createElement) {
    return createElement(
      'p'.// Label name
      this.message.toString() // Array of child nodes)},Copy the code
  • Other points to note:
    • With Webpack vue-loader, templates are compiled in the development environment
    • Vue components can use Render instead of template. React uses render by default

Vi. Vue component rendering/update process

  • Initial rendering process
    1. Parse the template as the Render function (or completed in the development environment, vue-loader)
    2. Render vnode, patch(elem,vnode)
    3. Trigger reactive, listen for the data property getter
  • The update process
    1. Modify data to fire the setter (previously listened on in the getter)
    2. Re-execute the render function to generate newVnode
    3. Compare old and new VNodes, patch(vNode,newVnode), and update to dom

Vii. Performance optimization of Vue3.0

The performance is 1.2 ~ 2 times faster than vue2. X

  • Static markup: The diff method for optimizing the virtual DOM in vue2. X is used for full comparison. Vue3.0 added static tags. When comparing with the last virtual node, only the node with the patch Flag is compared, and the specific content of the current node to be compared can be known according to the flag information.

  • Static promotion: Vue2. X is recreated each time, regardless of whether an element is updated or not, and then rendered. For elements that do not participate in the update, vue3.0 will do static promotion. They will only be created once and can be reused directly during rendering.

  • Event listener caching: By default, events such as onClick are treated as dynamically bound, so they are tracked every time they change, but because they are the same function, they can be cached and reused.

review

  • What is Vue? What problem was solved?
  • The MVVM architecture
  • Three elements (responsive, template compilation, VDOM/DIFF algorithm)
  • Component rendering/update process
  • Asynchronous rendering
    • $nextTick
    • Summarize data changes and update the view once
    • Reduce DOM operations and improve performance

reference

  • Vue diff algorithm execution process analysis
  • Diff algorithm illustrated animation
  • How does Vue3.0 get faster