Vue.js source code analysis (2) -- virtual DOM

1. Introduction to h() function

h()The function implements the overloading mechanism and can pass multiple parameter types. h(tag,data,children):
Parameter 1: The option object of the label selector or component
Parameter 2: Set properties or events for the label
Parameter 3: String (content)/array (sub-element)
Use case:

const vm = new Vue({
    
    
  el: '#demo',
  render(h) {
    
    
    const vNode = h('h1', {
    
    attrs: {
    
    id: 'box'}}, this.person)
    console.log(vNode)
    return vNode
  },
  data() {
    
    
    return {
    
    
      person: 'ls'
    }
  },
})

This code will create a virtual DOM: vNode, and will create the corresponding real DOMand fill it in el.
Insert image description here

2. The creation process of virtual DOM

render()Function accepts a h()function as parameter. vm.$createElement()As render()a h()function, when creating a virtual DOM, it is executed vm.$createElement(). This is just an initialization definition, and the actual execution is performed
Insert image description here
during rendering when initializing rendering . WatcherReference notes: Chapter 5 of initial renderingwatcher.get() will be executed updateComponent(). In this function, vm._render()virtual generation will be called DOM. vm._update()Generate real DOMupdate view.

2. Render view

vm._update()It is used to update the view, and the key code inside it is called vm.__patch__(). This function is the key to updating the view. vm.__patch__()The definition is as follows:
src/platforms/web/runtime/index.ts

Vue.prototype.__patch__ = inBrowser ? patch : noop

Determine the current environment. If it is a browser environment, assign a value patch(). If it is a non-browser environment, the value is an empty function. Then let’s look at patch()the function:
src/platforms/web/runtime/patch.ts

export const patch: Function = createPatchFunction({
    
     nodeOps, modules })

createPatchFunction()The function is a high-order function that will return a function internally. Let’s take a look at the execution process of the function patch()returned internally : it is roughly the same as the implementation of the library we looked at before . Use the diff algorithm to compare the differences between the old and new nodes. You can refer to: Implementation Principles of Virtual DOMpatch()
Insert image description here
updateChildren()SnabbDOM

Guess you like

Origin blog.csdn.net/weixin_45855469/article/details/131936259