vue operating mechanism

vue operating mechanism

[Image dump the chain fails, the source station may have security chain mechanism, it is recommended to save the picture down uploaded directly (img-oZPPdV43-1583663123391) (./ imgs / vue operating mechanism .png)]

Vue execution core is divided into several stages:

1) template compilation: generate render function reusable

2) Responsive: by listening Object.definedProperty to get and set object properties, two-way binding

3) Initial render: render function execution, the value of access to data in, will be monitored get, call the patch method to generate vdom

4) Data change: change will trigger data set, will be updated re-render, by the method of comparison of the old and new patch vnode, update the view

How to parse template Vue

  • What is Template

    • Essence: template is a string

    • Html format with like, but the template is logical, JS variables can be embedded, such as v-if, v-for other

    • View generated by the template eventually need to show html

    • Template must first be converted into JS code

      • There are logical (v-if, v-for), must be implemented (Turing complete) to use JS

      • Convert html to render the page, you must be implemented in order to JS

      • Therefore, to be converted into a template render function

  • render function

    • render function template contains all of the information, the return vnode, solved the template logic (v-if, v-for) issues

    • How to find the final render function generated
      find vue source, render src / compiler / codegen / index.js, generate the function's return value

  • render function and vdom

    • Template generates html: vm._c

    • H achieve like functions and snabbdom in vm._c, are passed tags, attributes, sub-elements as parameters

    • Vue.js of vdom achieved draws snabbdom

    • updateComponent the patch is implemented in vdom

    • First page rendering execution updateComponent

    • In each modification data attributes, are performed updateComponent

Vue operating mechanism

The first step: to render template parsing function:

  • You must first know the generation function is to render packaging when, and why? webpack packed when we're using to vue-template-compiler of this loader, its role is to compile the template to render function, so that the compiler is the first step; responsive listening is the time to code execution.

  • Compilation compile into parse, optimize, generate three parts

    • parse: parsing the template into an abstract syntax tree

    • optimize: each re-rendering, DOM, there is no need to change the part, which we call static sub-trees, the storage portion can be separated into a constant, then the process does not re-render rendering it again, and patch process behind no longer ignore it, such as our common basic html's header does not change.

    • generate: generate a virtual ast The process generates dom tree, i.e. the vnode ($ {code} is in the code), also generate further optimize static tree.

    function generate (
      ast: ASTElement | void,
      options: CompilerOptions
    ): CodegenResult {
      const state = new CodegenState(options)
      const code = ast ? genElement(ast, state) : '_c("div")'
      return {
        render: `with(this){return ${code}}`,
        staticRenderFns: state.staticRenderFns
      }
    }
    

vue demo

<div id="app">
  <p>普通属性:{{ message }}</p>
  <p>{{msg()}}</p>
  <p>{{ct}}</p>
  <input v-model="message">
  <div v-for="item in items">
      {{ item.text }}
    </div>
    <button v-on:click="bindClick">点我抓同伟</button>
</div>

// js
new Vue({
  el: '#app',
  data: {
    message: '以vue的名义',
    items: [{
        text: '达康书记'
    }, {
        text: '育良书记'
    }]
  },
  methods: {
    bindClick: function() {
        this.message = '这就抓同伟去';
    },
    msg: function() {
        return this.message + "这个方法每次都会执行";
    }
  },
  computed: {
    ct: function() {
        return this.message + "计算属性并不会每次都执行";
    }
  }
})

Corresponding to render function

with(this) {
    return _c('div', {
        attrs: {
            "id": "app"
        }
    },
    [_c('p', [_v("普通属性:" + _s(message))]), _v(" "), _c('p', [_v(_s(msg()))]), _v(" "), _c('p', [_v(_s(ct))]), _v(" "), _c('input', {
        directives: [{
            name: "model",
            rawName: "v-model",
            value: (message),
            expression: "message"
        }],
        domProps: {
            "value": (message)
        },
        on: {
            "input": function($event) {
                if ($event.target.composing) return;
                message = $event.target.value
            }
        }
    }), _v(" "), _l((items),
    function(item) {
        return _c('div', [_v("\n\t\t  " + _s(item.text) + "\n\t   ")])
    }), _v(" "), _c('button', {
        on: {
            "click": bindClick
        }
    },
    [_v("点我出奇迹抓同伟")])], 2)
}
  • data information template variables have become js

  • v-model template, v-if, v-for js logic into a

  • render function returns the virtual tree vnode, as detailed https://www.jianshu.com/p/fc0084c97e05

Step two: Responsive start listening

  • By listening to the object properties Object.definedProperty get and set, the process is encapsulated in the Observer

  • The data on the properties of the agent to vm

The third step: the first rendering, display the page and binding dependencies

  • Initial rendering, execution updateComponent (responsible patch), execute vm._render ()

  • Render function execution, accesses data in the data, will be responsive to get access to the monitor, the collect get dependent (Watcher) was added to a message subscriber (Dep) in

  • Execution updateComponent, will come in the patch method dom

  • patch will vdom rendered into real dom, for the first time rendering is complete

  • Question: Why should we listen get, rather than set?

    • Because the data in the many properties, some have been used, some not being used

    • Only to be used in the property will go get

    • If you do not go get, then set the time do not care

    • This avoids unnecessary rendering

Step four: data changes, it will trigger re-render

  • data changes, set to monitor

  • set the execution updateComponent

  • updateComponent re-run vm._render ()

  • Vnode newly generated and before vnode contrast, by comparing patch

  • The difference render to html

Reference:
https://www.cnblogs.com/dora-zc/p/11111813.html#vue-%E5%A6%82%E4%BD%95%E8%A7%A3%E6%9E%90%E6 % A8% A1% E6% 9D % BF

Published 59 original articles · won praise 22 · views 40000 +

Guess you like

Origin blog.csdn.net/Albert_Ejiestein/article/details/104737629