• 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钩子。

  • 相关阅读:
    粘滞位和vim的使用
    Java版本+企业电子招投标系统源代码+支持二开+招投标系统+中小型企业采购供应商招投标平台
    计算机公共课面试常见问题:线性代数篇
    python多线程时写入文本文件
    拷贝assets资源目录下xml文件到sdcard
    阿里P8大佬,耗时三年心血出品的Spring实战全家桶,涨薪8K的秘密
    C#的MessagePack(unity)--01
    redis为什么快,消息队列,单线程
    索引数据结构千千万 , 为什么B+Tree独领风骚
    postgresql11 主从配置详解
  • 原文地址:https://blog.csdn.net/denglouhen/article/details/125524926