• Vue2.0 瞧一下vm.$mount()


    vm.$mount()不经常用,因为在我们实例化Vue的时候我们可以传入属性el: "#app",目的在于将实例挂载到DOM元素下,但如果不传el选项,就需要手动挂载,这个时候唯一的方法就是调用$mount()方法。

    就像在vue项目的main.js里我们经常会写到这样一句话:

    new Vue({

        xxxx

    }).$mount("#app");

    $mount()函数的表现在完整版和只包含运行时版本之间有差异,差异在于编译过程,也就是完整版会首先检查template或者el选项提供的模板是否已经转换为渲染函数,如果没有,就要先编译为渲染函数,再进入挂载流程。所以两个版本之间是包含关系。

    通过函数劫持方法,来拓展核心功能来实现完整版,首先判断$options上是否有render,如果没有,再取template选项,如果仍没有,再取el选项中的模板。之后通过compileToFunctions函数生成渲染函数赋值给options.render。这部分就是差异之处具体在做的事情。

    那么只包含运行时版本就涵盖了$mount方法的核心功能:

    Vue.prototype.$mount = function (

      el?: string | Element,

      hydrating?: boolean

    ): Component {

      el = el && inBrowser ? query(el) : undefined

      return mountComponent(this, el, hydrating)

    }

    mountComponent()首先还是会校验render,如果没有则会返回一个注释类型的VNode节点。

    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') {

         // 一些警告

        }

      }

      callHook(vm, 'beforeMount')

      ......

      // 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

      new Watcher(vm, updateComponent, noop, {

        before () {

          if (vm._isMounted && !vm._isDestroyed) {

            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

      if (vm.$vnode == null) {

        vm._isMounted = true

        callHook(vm, 'mounted')

      }

      return vm

    }

    然后触发beforeMount钩子。这之后执行真正的挂载操作。vm._update(vm._render())就是调用渲染函数得到最新的虚拟树节点,然后通过_update方法和上一次的旧的VNode对比并更新DOM。new Watcher可以实现挂载的持续性,在这个过程中,每次有新的数据渲染更新,会触发beforeUpdate钩子。整个挂载完成之后,就会触发mounted钩子。

  • 相关阅读:
    iTOP-RK3399开发板驱动模块传数组
    Prism个人学习笔记
    单片机原理与接口技术(ESP8266/ESP32)机器人类草稿
    一文速通 css3 2D转换【内含开发常用效果实现】
    网络安全 — SASE — SASE Cloud and Services
    智慧旅游管理系统下的旅游业的发展规划
    Java入门第112课——使用Iterator的hasNext方法、next方法遍历集合
    组合模式(Composite Pattern)
    2.1配置(AutoMapper官方文档翻译)
    软考 系统架构设计师系列知识点之基于架构的软件开发方法ABSD(7)
  • 原文地址:https://blog.csdn.net/denglouhen/article/details/125524926