vue源码分析——$mount方法

208 阅读1分钟

$mount主要调用三个文件

  1. src/platforms/web/entry-runtime-with-compiler.js(入口文件)

  2. src/platforms/wen/runtime/index.js (定义了原型上的原型上的 $mount 方法)

    这种设计方式,完全是因为代码可以复用,因为它是可以被 runtime only 版本的 Vue 直接使用。因为 在 Vue 2.0 版本中,所有 Vue 的组件的渲染最终都需要 render 方法,如果使用runtimeOnly的vue版本,运行的时候是不带编译的,编译是在离线的时候做的(通过webpack做)

// 如果是第一种未编译,那么我们需要用到entry-runtime-with-compiler文件中的$mount方法,把template、el转变为render,如果是第二种,webpack编译后就直接使用render,所以我们直接使用src/platforms/wen/runtime/index.js 中的$mount方法即可
// 未编译
new Vue({

  template: '{{ hi }}'

})
// webpack编译后
new Vue({
  render (h) {

    return h('div', this.hi)

  }
})
  1. 在2的文件上(原型上的$mount),调用了mountComponent方法,该方法定义src/core/instance/lifecycle.js文件中

文件注解说明

1、 src/platforms/web/entry-runtime-with-compiler.js

  1. 如果生成vue实例的时候,有render方法、templete、el,他们的执行顺序是render => templete => el 如果没有定义 render 方法,则会把 el 或者 template 字符串转成 render 方法。需要注意的是: 在 Vue 2.0 版本中,所有 Vue 的组件的渲染最终都需要 render 方法,无论是用单页面 .vue 方式开发,还是写了 el 或者 template 属性,最终都要被转成 render 方法,那么这个过程是 Vue 的一个 “在线编译” 的过程, 它是调用 compileToFunctions 方法实现的,最后调用原型上的 $mount 方法挂载
new Vue({
  render: h => h(App),
}).$mount('#app')
源码截图说明

image.png

流程图说明

image.png

compileToFunctions方法的使用说明
  1. createCompilerCreator(放在'compiler/create-compiler.js'里面),改方法返回了compile, compileToFunctions

image.png

1. compile方法 在该方法内会编译模板,把模板生产render和抽象语法树ast
编译后,抽象语法树的结构

image.png

render的结构

image.png

2. compileToFunctions,通过调用compile方法把模板编译完,并且记录缓存。下次不用再次编译,同时,把编译后的render和staticRenderFns对象转变为Funciton

    

2、 src/core/instance/lifecycle.js