VUEソースコード学習の6番目の部分-新しいVueの機能(マウント)

1.概要

  前のパーツがすべて準備である場合、マウントの最初から、ページがレンダリングされるまで正式なレンダリング作業に入ります。コードの分析を始める前に、何をすべきかについて考えることができます。

1.テンプレート内の変数と式を実際の値に置き換えます。たとえば、次のとおりです。

 <div id="app">
   <ul>
    <li v-for="item in items">
      {{item.id}}
    </li>
  </ul>
<div>

..
var vm = new Vue({
    el:"#app",
    data:{
       items:[
        {id:1},
        {id:2},
        {id:3}
      ]
    }
})

交換後、実際のdomが形成およびレンダリングされます

<div id="app">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
<div>

2.更新メカニズムを確立するデータが更新されると、DOMも再レンダリングされます。たとえば、items配列が更新されると、それに応じてドームも更新されます。

実際、vueもこれらの2つのポイントの周りにあります。以下は、マウントプロセスの概略図です。

(1)HTML文字列の抽出は、それがelであろうとテンプレートであろうと、最終的にHTML文字列を抽出します。

(2)html文字列をコンパイルしてAST抽象番号にコンパイルし、それをスプライスしてレンダリング式にします。

(3)実際のdomを形成するために、レンダリングはvnodeに変換され、最後に実際のdomが生成され、更新されたモニタリングが追加されます。

以下では、ソースコードから分析します。この部分には、より多くのコンテンツと知識ポイントが含まれます。一部のコンテンツは、紹介する特別な章として戻されます。

第二に、コンパイル時の$マウント

    Vueの$マウント定義は、src / platform / web / entry-runtime-with-compiler.js、src / platform / web / runtime / index.jsの2つのファイルに表示されます。テンプレート文字列はレンダー構文に変換され、次にdomのレンダリングを完了するために次のファイルのマウントが呼び出されます。つまり、コンパイルプロセスはentry-runtime-with-compiler.jsに実装されています。レンダー構文を使用する場合は、実行時にマウントを呼び出すだけでよいため、コンパイル時間を節約できます。しかし、実際の開発では、テンプレートモードを使用することをお勧めします。結局のところ、読みやすさは向上します。

entry-runtime-with-compiler.jsの$マウントを見てみましょう

Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  //根据id获取dom元素
  el = el && query(el)

  /* istanbul ignore if */
  if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== 'production' && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )
    return this
  }

  const options = this.$options
  // resolve template/el and convert to render function
  //1、根据template/el,获取html的字符串
  if (!options.render) {
    //获取template
    let template = options.template
    if (template) {
      if (typeof template === 'string') {
        if (template.charAt(0) === '#') {
          template = idToTemplate(template)
          /* istanbul ignore if */
          if (process.env.NODE_ENV !== 'production' && !template) {
            warn(
              `Template element not found or is empty: ${options.template}`,
              this
            )
          }
        }
      } else if (template.nodeType) {
        template = template.innerHTML
      } else {
        if (process.env.NODE_ENV !== 'production') {
          warn('invalid template option:' + template, this)
        }
        return this
      }
    } else if (el) {
      template = getOuterHTML(el)
    }
     //2、编译,生成render
    if (template) {
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile')
      }
      const { render, staticRenderFns } = compileToFunctions(template, {
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      options.render = render
      options.staticRenderFns = staticRenderFns

      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile end')
        measure(`vue ${this._name} compile`, 'compile', 'compile end')
      }
    }
  }
  //3、调用runtime的mount
  return mount.call(this, el, hydrating)
}

この方法は主に実現されます

1. elまたはテンプレートに従って、上記の例のようなhtml文字列、取得したコンテンツを取得します。

「<div id = "app">
  <ul>
    <li v-for = "item in items">
      {{item.id}}
    </ li>
  </ ul>
</ div>」

2.文字列をレンダー関数式に変換します。以前にレンダーの式も導入しましたが、reactに精通している学生はこれに精通しているはずです。このプロセスにはコンパイルが含まれます。分析する専用の章があります。最終変換後のレンダリング関数:

f() {
with(this){return _c('div',{attrs:{"id":"app"}},[_c('ul',_l((items),function(item){return _c('li',[_v("\n      "+_s(item.id)+"\n    ")])}))])}
}

3. runtime / index.jsでマウント定義を呼び出し、後続のプロセスを続行します。

4.実行時にマウント

テンプレート(またはelが指す外部HTML)がコンパイルされてレンダリング関数に変換された後、実行時マウントが実際のマウントプロセスを担当します。レンダリング式をvnodeに変換し、最終的に実際のdomノードを作成します。

Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}

   マウントには2つのel入力パラメーターがあります。1つ目は、マウントされた要素を表すことです。  これは、文字列またはDOMオブジェクトにすることができます。文字列が文字列の場合は、query メソッドを呼び出し  てDOMオブジェクトに変換します。2番目のパラメーターはサーバー側のレンダリングに関連しており、ブラウザー環境では2番目のパラメーターを渡す必要はありません。

mountComponentメソッドが返されました。

export function mountComponent (
  vm: Component,
  el: ?Element,
  hydrating?: boolean
): Component {
  vm.$el = el
  if (!vm.$options.render) {
    vm.$options.render = createEmptyVNode
    if (process.env.NODE_ENV !== 'production') {
      /* istanbul ignore if */
      if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
        vm.$options.el || el) {
        warn(
          'You are using the runtime-only build of Vue where the template ' +
          'compiler is not available. Either pre-compile the templates into ' +
          'render functions, or use the compiler-included build.',
          vm
        )
      } else {
        warn(
          'Failed to mount component: template or render function not defined.',
          vm
        )
      }
    }
  }
  //1、挂载前,执行beforMount
  callHook(vm, 'beforeMount')

  let updateComponent
  /* istanbul ignore if */
  if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
    updateComponent = () => {
      const name = vm._name
      const id = vm._uid
      const startTag = `vue-perf-start:${id}`
      const endTag = `vue-perf-end:${id}`

      mark(startTag)
      const vnode = vm._render()
      mark(endTag)
      measure(`vue ${name} render`, startTag, endTag)

      mark(startTag)
      vm._update(vnode, hydrating)
      mark(endTag)
      measure(`vue ${name} patch`, startTag, endTag)
    }
  } else {
    //2、定义updateComponent,vm._render将render表达式转化为vnode,vm._update将vnode渲染成实际的dom节点
    updateComponent = () => {
      vm._update(vm._render(), hydrating)
    }
  }

  // we set this to vm._watcher inside the watcher's constructor
  // since the watcher's initial patch may call $forceUpdate (e.g. inside child
  // component's mounted hook), which relies on vm._watcher being already defined
  //3、首次渲染,并监听数据变化,并实现dom的更新
  new Watcher(vm, updateComponent, noop, {
    before () {
      if (vm._isMounted) {
        callHook(vm, 'beforeUpdate')
      }
    }
  }, true /* isRenderWatcher */)
  hydrating = false

  // manually mounted instance, call mounted on self
  // mounted is called for render-created child components in its inserted hook
  //4、挂载完成,回调mount函数
  if (vm.$vnode == null) {
    vm._isMounted = true
    callHook(vm, 'mounted')
  }
  return vm
}

完全な取り付けプロセスをここに示します。

1. beforeMountコールバックメソッドを実行します。この時点で、elはvm。$ Elに割り当てられています。Vueの--new VUEソースタイトルIII試験(概要)どのように行われているサンプルは、例えば、ELはすでに値を持っています。

 beforeMount(){
    console.log("beforeMount");
     console.log("this el:"+this.$el);//[object HTMLDivElement]
     console.log("this data:"+this.$data);//[object Object]
     console.log("this msg:"+this.msg);//tttt
   }

2. updateComponentメソッドvm._renderを定義してレンダー式をvnodeに変換し、vm._updateを定義してvnodeを実際のdomにレンダリングします。

3.ウォッチャーインスタンスを作成します。2つの機能があります。

(1)updateComponentメソッドを実行してdomのレンダリングを実現し、属性変数に対する式の依存コレクションを完成させます。

  (2)インクルードされた式の属性変数が変更されると、更新が再度実行されます。

ウォッチャー部分については、後の応答原理で分析され、現在のステージのみが理解されます。

4.ルートノードかどうかを判別し、マウント完了のコールバックメソッドを実行します。

次に、レンダリングと更新のプロセスに注目します。

5、vm._render

このメソッドは、レンダリング式をvnodeに変換するためのものです。最初に、vnodeとは何かを見てみましょう。vnodeは、core / vdom / vnode.jsにあり、次のように定義されています。

export default class VNode {
  tag: string | void;
  data: VNodeData | void;
  children: ?Array<VNode>;
  text: string | void;
  elm: Node | void;
  ns: string | void;
  context: Component | void; // rendered in this component's scope
  key: string | number | void;
  componentOptions: VNodeComponentOptions | void;
  componentInstance: Component | void; // component instance
  parent: VNode | void; // component placeholder node

  // strictly internal
  raw: boolean; // contains raw HTML? (server only)
  isStatic: boolean; // hoisted static node
  isRootInsert: boolean; // necessary for enter transition check
  isComment: boolean; // empty comment placeholder?
  isCloned: boolean; // is a cloned node?
  isOnce: boolean; // is a v-once node?
  asyncFactory: Function | void; // async component factory function
  asyncMeta: Object | void;
  isAsyncPlaceholder: boolean;
  ssrContext: Object | void;
  fnContext: Component | void; // real context vm for functional nodes
  fnOptions: ?ComponentOptions; // for SSR caching
  fnScopeId: ?string; // functional scope id support

  constructor (
    tag?: string,
    data?: VNodeData,
    children?: ?Array<VNode>,
    text?: string,
    elm?: Node,
    context?: Component,
    componentOptions?: VNodeComponentOptions,
    asyncFactory?: Function
  ) {
    /*当前节点的标签名*/
    this.tag = tag
    /*当前节点对应的对象,包含了具体的一些数据信息,是一个VNodeData类型,可以参考VNodeData类型中的数据信息*/
    this.data = data
    /*当前节点的子节点,是一个数组*/
    this.children = children
    /*当前节点的文本*/
    this.text = text
     /*当前虚拟节点对应的真实dom节点*/
    this.elm = elm
    /*当前节点的名字空间*/
    this.ns = undefined
    /*编译作用域*/
    this.context = context
    /*函数化组件作用域*/
    this.fnContext = undefined
    this.fnOptions = undefined
    this.fnScopeId = undefined
    /*节点的key属性,被当作节点的标志,用以优化*/
    this.key = data && data.key
    /*组件的option选项*/
    this.componentOptions = componentOptions
    /*当前节点对应的组件的实例*/
    this.componentInstance = undefined
     /*当前节点的父节点*/
    this.parent = undefined
    /*简而言之就是是否为原生HTML或只是普通文本,innerHTML的时候为true,textContent的时候为false*/
    this.raw = false
    /*静态节点标志*/
    this.isStatic = false
    /*是否作为跟节点插入*/
    this.isRootInsert = true
    /*是否为注释节点*/
    this.isComment = false
    /*是否为克隆节点*/
    this.isCloned = false
    /*是否有v-once指令*/
    this.isOnce = false
    /*异步组件的工厂方法*/
    this.asyncFactory = asyncFactory
    /*异步源*/
    this.asyncMeta = undefined
     /*是否异步的预赋值*/
    this.isAsyncPlaceholder = false
  }

  // DEPRECATED: alias for componentInstance for backwards compat.
  /* istanbul ignore next */
  get child (): Component | void {
    return this.componentInstance
  }
}

vnodeはdom属性のコレクションであり、簡素化されたdomと考えることができます。

vm._renderはsrc / core / instance / render.jsにあり、

  Vue.prototype._render = function (): VNode {
   ...
    try {
      //核心代码,生成vnode
      vnode = render.call(vm._renderProxy, vm.$createElement)
    } catch (e) {
      ...
    }
    // set parent
    vnode.parent = _parentVnode
    return vnode
  }

コアコードを直接見てみましょう。Vm._renderProxyは実行コンテキストです。前述のとおり、本番環境ではvmです。call関数がわからない場合は、vm.render(vm。$ CreateElement)に変換してください。 。

この例のrender関数を参照して、vm._cを呼び出してすべてのレベルでvnodeを作成します。このため、前の章で説明したinitRenderメソッドで、この関数はどこに定義されていますか

//定义._c方法,对template进行render处理的方法
  vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)

createElementはsrc / core / vdom / create-element.jsにあります

export function createElement (
  context: Component,
  tag: any,
  data: any,
  children: any,
  normalizationType: any,
  alwaysNormalize: boolean
): VNode | Array<VNode> {
   //处理data的入参,当没有data属性的情况下,这个参数表示的是children
  if (Array.isArray(data) || isPrimitive(data)) {
    normalizationType = children
    children = data
    data = undefined
  }
  if (isTrue(alwaysNormalize)) {
    normalizationType = ALWAYS_NORMALIZE
  }
  return _createElement(context, tag, data, children, normalizationType)
}

createElementは_createElementのカプセル化であり、さまざまな入力パラメーター書き込みメソッドを処理することがわかります。_createElementのコードを引き続き見てください。

export function _createElement (
  context: Component,
  tag?: string | Class<Component> | Function | Object,
  data?: VNodeData,
  children?: any,
  normalizationType?: number
): VNode | Array<VNode> {
  if (isDef(data) && isDef((data: any).__ob__)) {
    process.env.NODE_ENV !== 'production' && warn(
      `Avoid using observed data object as vnode data: ${JSON.stringify(data)}\n` +
      'Always create fresh vnode data objects in each render!',
      context
    )
    return createEmptyVNode()
  }
  // object syntax in v-bind
  if (isDef(data) && isDef(data.is)) {
    tag = data.is
  }
  if (!tag) {
    // in case of component :is set to falsy value
    return createEmptyVNode()
  }
  // warn against non-primitive key
  if (process.env.NODE_ENV !== 'production' &&
    isDef(data) && isDef(data.key) && !isPrimitive(data.key)
  ) {
    if (!__WEEX__ || !('@binding' in data.key)) {
      warn(
        'Avoid using non-primitive value as key, ' +
        'use string/number value instead.',
        context
      )
    }
  }
  // support single function children as default scoped slot
  if (Array.isArray(children) &&
    typeof children[0] === 'function'
  ) {
    data = data || {}
    data.scopedSlots = { default: children[0] }
    children.length = 0
  }

  //1、规整childern子节点
  if (normalizationType === ALWAYS_NORMALIZE) {
    children = normalizeChildren(children)
  } else if (normalizationType === SIMPLE_NORMALIZE) {
    children = simpleNormalizeChildren(children)
  }
  let vnode, ns
  //2、创建vnode
  if (typeof tag === 'string') {
    let Ctor
    ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag)
    if (config.isReservedTag(tag)) {
      // platform built-in elements
      vnode = new VNode(
        config.parsePlatformTagName(tag), data, children,
        undefined, undefined, context
      )
    } else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
      // component
      vnode = createComponent(Ctor, data, context, children, tag)
    } else {
      // unknown or unlisted namespaced elements
      // check at runtime because it may get assigned a namespace when its
      // parent normalizes children
      vnode = new VNode(
        tag, data, children,
        undefined, undefined, context
      )
    }
  } else {
    // direct component options / constructor
    vnode = createComponent(tag, data, context, children)
  }
  if (Array.isArray(vnode)) {
    return vnode
  } else if (isDef(vnode)) {
    if (isDef(ns)) applyNS(vnode, ns)
    if (isDef(data)) registerDeepBindings(data)
    return vnode
  } else {
    return createEmptyVNode()
  }
}

    5つの入力パラメーターがあります。contextはコンテキストを表します。つまり、現在のコンポーネントオブジェクト、tagはノードのラベルを表します。dataはコンポーネントのデータデータを表します。VNodeタイプ、childrenは現在の子ノードを表します、normalizationTypeは子ノードの仕様タイプを表します。 renderメソッドは整理する必要があります。

  このメソッドには主に、子の正規化とvnodeの作成という2つの関数が含まれています。

1.通常の子供

// 1. When the children contains components - because a functional component
// may return an Array instead of a single root. In this case, just a simple
// normalization is needed - if any child is an Array, we flatten the whole
// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
// because functional components already normalize their own children.
export function simpleNormalizeChildren (children: any) {
  for (let i = 0; i < children.length; i++) {
    if (Array.isArray(children[i])) {
      return Array.prototype.concat.apply([], children)
    }
  }
  return children
}

// 2. When the children contains constructs that always generated nested Arrays,
// e.g. <template>, <slot>, v-for, or when the children is provided by user
// with hand-written render functions / JSX. In such cases a full normalization
// is needed to cater to all possible types of children values.
export function normalizeChildren (children: any): ?Array<VNode> {
  return isPrimitive(children)
    ? [createTextVNode(children)]
    : Array.isArray(children)
      ? normalizeArrayChildren(children)
      : undefined
}

simpleNormalizeChildrenは、機能コンポーネントの処理を参照します。機能コンポーネントは、ルートノードの代わりに配列を返します。Array.prototype.concatを介して配列をフラット化して、1層だけの深さにする必要があります。

NormalizeChildrenは、手書きのレンダリング関数またはJSXを処理します。子が基本型の場合、TextvnodeノードはcreateTextVNodeによって作成されます。v-forとスロットのコンパイル時にネストされた配列が生成されると、normalizeArrayChildrenが呼び出されます。

子供の規制後、子供はタイプVNodeの配列になります。

2. vnodeを作成する

最初にタグのタイプがStringかどうかを判別し、次にそれが組み込みタグ(div、bodyなどのhtmlまたはsvgタグ)かどうかを判別します。そうである場合は、通常のVNodeを作成し、タグ、データ、子、その他の変数を初期化します。

登録済みコンポーネントの場合は、createComponentを呼び出してVNodeを作成します。それ以外の場合は、不明なラベルを持つVNodeを作成します。Stringタイプでない場合は、createComponentを呼び出してコンポーネントタイプVNodeを作成します。コンポーネントの作成プロセスについては後で説明します。

つまり、createElementが作成された後で、仮想DOMであるvnodeツリーが作成されます。

六、vm._update

vm._updateは、vnodeを実際のdomノードにレンダリングします。呼び出される場所は2つあり、1つ目は最初のレンダリング、2つ目はデータの更新です。この章では、最初のケースのみに焦点を当てます。分析のために特別な章でデータを更新します。vm._updateはsrc / core / instance / lifecycle.jsで定義されています。

 Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
    ...
    if (!prevVnode) {
      // initial render
      vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
    } else {
      // updates
      vm.$el = vm.__patch__(prevVnode, vnode)
    }
    ...
  }

コアコードを見て、最初のレンダリングのためにvm .__ patch__を呼び出しましょう。Webプラットフォームはsrc / platform / web / runtime / index.jsで定義されています

// install platform patch function
Vue.prototype.__patch__ = inBrowser ? patch : noop

ブラウザ環境の場合は、src / platforms / web / runtime / patch.jsです(サーバー側のレンダリングには不要で、空の関数です)。

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

createPatchFunctionは、src / core / vdom / patch.jsで定義されたパッチ関数を返します。

export function createPatchFunction (backend) {
...
  return function patch (oldVnode, vnode, hydrating, removeOnly) {
    if (isUndef(vnode)) {
      if (isDef(oldVnode)) invokeDestroyHook(oldVnode)
      return
    }

    let isInitialPatch = false
    const insertedVnodeQueue = []

    if (isUndef(oldVnode)) {
      // empty mount (likely as component), create new root element
      isInitialPatch = true
      createElm(vnode, insertedVnodeQueue)
    } else {
      //是否是实际的元素
      const isRealElement = isDef(oldVnode.nodeType)
      if (!isRealElement && sameVnode(oldVnode, vnode)) {
        // patch existing root node
        patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly)
      } else {
        if (isRealElement) {
          // mounting to a real element
          // check if this is server-rendered content and if we can perform
          // a successful hydration.
          if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) {
            oldVnode.removeAttribute(SSR_ATTR)
            hydrating = true
          }
          if (isTrue(hydrating)) {
            if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
              invokeInsertHook(vnode, insertedVnodeQueue, true)
              return oldVnode
            } else if (process.env.NODE_ENV !== 'production') {
              warn(
                'The client-side rendered virtual DOM tree is not matching ' +
                'server-rendered content. This is likely caused by incorrect ' +
                'HTML markup, for example nesting block-level elements inside ' +
                '<p>, or missing <tbody>. Bailing hydration and performing ' +
                'full client-side render.'
              )
            }
          }
          // either not server-rendered, or hydration failed.
          // create an empty node and replace it
          //转成vnode
          oldVnode = emptyNodeAt(oldVnode)
        }

        // replacing existing element
        const oldElm = oldVnode.elm
        const parentElm = nodeOps.parentNode(oldElm)

        // create new node
        //核心方法,根据vnode渲染成实际的dom
        createElm(
          vnode,
          insertedVnodeQueue,
          // extremely rare edge case: do not insert if old element is in a
          // leaving transition. Only happens when combining transition +
          // keep-alive + HOCs. (#4590)
          oldElm._leaveCb ? null : parentElm,
          nodeOps.nextSibling(oldElm)
        )

        // update parent placeholder node element, recursively
        if (isDef(vnode.parent)) {
          let ancestor = vnode.parent
          const patchable = isPatchable(vnode)
          while (ancestor) {
            for (let i = 0; i < cbs.destroy.length; ++i) {
              cbs.destroy[i](ancestor)
            }
            ancestor.elm = vnode.elm
            if (patchable) {
              for (let i = 0; i < cbs.create.length; ++i) {
                cbs.create[i](emptyNode, ancestor)
              }
              // #6513
              // invoke insert hooks that may have been merged by create hooks.
              // e.g. for directives that uses the "inserted" hook.
              const insert = ancestor.data.hook.insert
              if (insert.merged) {
                // start at index 1 to avoid re-invoking component mounted hook
                for (let i = 1; i < insert.fns.length; i++) {
                  insert.fns[i]()
                }
              }
            } else {
              registerRef(ancestor)
            }
            ancestor = ancestor.parent
          }
        }

        // destroy old node
        if (isDef(parentElm)) {
          removeVnodes(parentElm, [oldVnode], 0, 0)
        } else if (isDef(oldVnode.tag)) {
          invokeDestroyHook(oldVnode)
        }
      }
    }

    invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
    return vnode.elm
  }
...
}

CreatePatchFunctionは一連のメソッドを内部的に定義し、最後にpatchメソッドを返します。これには4つのパラメーターがあり、実際にはvm .__ patch __(vm。$ el、vnode、hydrating、false)で渡されます。また、最初の例としてvmを取り上げます。$ ElはアプリのIDを持つdom、vnodeはレンダリング後の仮想オブジェクト、ハイドレイティングはサーバー側レンダリングかどうかを示し、最後のパラメーターremoveOnly はtransition-group 使用するための  ものです。

 oldVnodeは、IDがappである実際のdomであるため、isRealElementはtrueであり、emptyNodeAtはoldVnodeをVnodeオブジェクトに変換します。次にcreateElmを呼び出して実際のdomを作成します。このメソッドに焦点を当てましょう。

 function createElm (
    vnode,
    insertedVnodeQueue,
    parentElm,
    refElm,
    nested,
    ownerArray,
    index
  ) {
    if (isDef(vnode.elm) && isDef(ownerArray)) {
      // This vnode was used in a previous render!
      // now it's used as a new node, overwriting its elm would cause
      // potential patch errors down the road when it's used as an insertion
      // reference node. Instead, we clone the node on-demand before creating
      // associated DOM element for it.
      vnode = ownerArray[index] = cloneVNode(vnode)
    }

    vnode.isRootInsert = !nested // for transition enter check
    if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
      return
    }

    const data = vnode.data
    const children = vnode.children
    const tag = vnode.tag
    //1、合法性校验
    if (isDef(tag)) {
      if (process.env.NODE_ENV !== 'production') {
        if (data && data.pre) {
          creatingElmInVPre++
        }
        if (isUnknownElement(vnode, creatingElmInVPre)) {
          warn(
            'Unknown custom element: <' + tag + '> - did you ' +
            'register the component correctly? For recursive components, ' +
            'make sure to provide the "name" option.',
            vnode.context
          )
        }
      }
      //2、创建该vnode的dom元素
      vnode.elm = vnode.ns
        ? nodeOps.createElementNS(vnode.ns, tag)
        : nodeOps.createElement(tag, vnode)
      setScope(vnode)

      /* istanbul ignore if */
      if (__WEEX__) {
        // in Weex, the default insertion order is parent-first.
        // List items can be optimized to use children-first insertion
        // with append="tree".
        const appendAsTree = isDef(data) && isTrue(data.appendAsTree)
        if (!appendAsTree) {
          if (isDef(data)) {
            invokeCreateHooks(vnode, insertedVnodeQueue)
          }
          insert(parentElm, vnode.elm, refElm)
        }
        createChildren(vnode, children, insertedVnodeQueue)
        if (appendAsTree) {
          if (isDef(data)) {
            invokeCreateHooks(vnode, insertedVnodeQueue)
          }
          insert(parentElm, vnode.elm, refElm)
        }
      } else {
        //3、创建子节点
        createChildren(vnode, children, insertedVnodeQueue)
        //4、执行所有的create钩子
        if (isDef(data)) {
          invokeCreateHooks(vnode, insertedVnodeQueue)
        }
        //5、插入节点
        insert(parentElm, vnode.elm, refElm)
      }

      if (process.env.NODE_ENV !== 'production' && data && data.pre) {
        creatingElmInVPre--
      }
    } else if (isTrue(vnode.isComment)) {
      vnode.elm = nodeOps.createComment(vnode.text)
      insert(parentElm, vnode.elm, refElm)
    } else {
      vnode.elm = nodeOps.createTextNode(vnode.text)
      insert(parentElm, vnode.elm, refElm)
    }
  }

まず、タグの有効性を確認し、nodeOps.createElementを使用して要素を作成します。src / plateforms / web / runtime / node-ops.jsにあるこのメソッドを見てみましょう

export function createElement (tagName: string, vnode: VNode): Element {
  //核心方法
  const elm = document.createElement(tagName)
  if (tagName !== 'select') {
    return elm
  }
  // false or null will remove the attribute but undefined will not
  if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) {
    elm.setAttribute('multiple', 'multiple')
  }
  return elm
}

最後に、ネイティブメソッドdocument.createElementが呼び出され、setAttributeがdomノードの作成を実装します。

次に、createChildrenメソッドを呼び出して子ノード要素を作成します。

function createChildren (vnode, children, insertedVnodeQueue) {
    //如果有子节点,则调用creatElm递归创建
    if (Array.isArray(children)) {
      if (process.env.NODE_ENV !== 'production') {
        checkDuplicateKeys(children)
      }
      for (let i = 0; i < children.length; ++i) {
        createElm(children[i], insertedVnodeQueue, vnode.elm, null, true, children, i)
      }
    } else if (isPrimitive(vnode.text)) {//对于叶节点,直接添加text
      nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text)))
    }
  }

子ノードがある場合は、creatElmを呼び出すことで再帰的に作成され、リーフノードの場合は要素に直接追加されます。

子ノードの要素が作成された後、invokeCreateHooks メソッドを呼び出して  createのすべてのフックを実行し、vnode それらにフックを  プッシュします  insertedVnodeQueue 。

最後にinsertを呼び出して、domを親要素に挿入します。これは再帰呼び出しであるため、子要素は親要素の前に挿入する必要があります。挿入プロセス中に、要素を挿入するためにネイティブのappendChildが呼び出されます。

この例では、作成と挿入の順序はli-> ul-> divであり、最後に完成したDOMが本文に挿入されます。

この時点で、最初のレンダリングが完了した後、最終的にcreateElement、setAttribute、appendChildなどのネイティブメソッドが使用され、ノードの作成が行われていることがわかります。

7.まとめ

さまざまな初期化とマウントによって、新しいVueも終了し、元のデータとテンプレートが最終的に実際のDOMにレンダリングされます。以下は前任者によって要約されたプロセスの概要ですが、それは非常に良い、シンプルで明確であると思います。

分析プロセス全体を通じて、できるだけ多くの詳細を無視しているため、誰もがメインラインを明確に理解できます。次の章では、この知識を学ぶ必要があります。

公開された33元の記事 ウォン称賛95 ビュー30000 +

おすすめ

転載: blog.csdn.net/tcy83/article/details/86566589