当前位置: 代码迷 >> 综合 >> Vue 源码分析step_2 - 源码层面的 Vue 实例和编译器
  详细解决方案

Vue 源码分析step_2 - 源码层面的 Vue 实例和编译器

热度:33   发布时间:2024-02-20 22:32:07.0

顾及到使用 Vue 的所有场景,今后分析的版本全部为完全的 vue 版本,即带编译器的版本。在 entry-runtime-with-compiler.js 中,有这么一个代码:

// 引入 Vue 构造函数供外部使用
import Vue from './runtime/index'//引入编译函数
import { compileToFunctions } from './compiler/index'

在对 Vue 版本以及版本之间的区别有一个较浅的认识之后,接下来分析 import Vue 分支

import vue:

  • 导入了核心源码中暴露出来的 Vue
  • 挂载了 patch 方法

runtime/index:

/* @flow */import Vue from 'core/index'
import { mountComponent } from 'core/instance/lifecycle'
import { inBrowser } from 'core/util/index'import { patch } from './patch'// 给全局挂在 patch 方法
// install platform patch function
Vue.prototype.__patch__ = inBrowser ? patch : noop// public mount method
// 挂在 mount 方法
Vue.prototype.$mount = function (el?: string | Element,hydrating?: boolean
): Component {...
}export default Vue

接下来分import Vue from 'core/index' 和 Vue.prototype.__patch__ = inBrowser ? patch : noop 两个方面进行讨论。首先是引入了核心模块中的 index:

import Vue from './instance/index'
import { initGlobalAPI } from './global-api/index'
// 初始化全局 api
initGlobalAPI(Vue)
// 爆漏出 Vue
export default Vue

可以看出来,核心源码里,执行了初始化全局 API 的函数,并且暴露出了vue


在./instance/index中进行了一系列的初始化行为,其实就是给原型挂载方法

import { initMixin } from './init'
import { stateMixin } from './state'
import { renderMixin } from './render'
import { eventsMixin } from './events'
import { lifecycleMixin } from './lifecycle'// 给 Vue 原型挂载_init 方法
initMixin(Vue)
// 给 Vue 原型挂载$data $props $set $delete $watch
stateMixin(Vue)
// 给 Vue原型挂载$on $once $emit $off 方法
eventsMixin(Vue)
// 给 Vue 原型挂载_update $forceupdate $destory 方法
lifecycleMixin(Vue)
// // 给 Vue原型挂载 _render, $nextTick 方法
renderMixin(Vue)// {
//   router,
//   store,
//   component: {}
// }
function Vue (options) {this._init(options)
}export default Vue

 

initGlobalAPI方法:

/* @flow */import { set, del } from '../observer/index'import {nextTick
} from '../util/index'// 初始化全局api, 以及注册,拓展,合并插件选项方法
export function initGlobalAPI (Vue) {Vue.set = setVue.delete = delVue.nextTick = nextTick// Vue.use - 注册插件initUse(Vue)// minixs 合并组件选项作为高阶组件initMixin(Vue)// extend 拓展组件initExtend(Vue)
}
  • 给全局挂载了 set,delete 方法,因为在 vue2.x 中,响应式原理通过 Objecr.definedProperty (或者设置数组的原型进行拦截来设定响应式),能监听到对象的变化,却不能监听到数据的新增或者删除。所以我们迫不得已的向外暴露出一个全局的 API,供我们手动调用,将这种新增或者删除操作,也变为响应式操作
  • 给实例挂载 nextTick 方法
  • 初始化 use 操作。为我们我们平时引入组件库,或者一些插件的时候去使用
  • 根据合并策略去合并组件参数选项
  • 初始化 initExtend 方法供我们扩展组件的时候去使用

import { compileToFunctions } from './compiler/index'

这里是引入了编译器

 
export const createCompiler = createCompilerCreator(function baseCompile (template: string,options: CompilerOptions
): CompiledResult {// 第一步 模板被解析成为了 astconst ast = parse(template.trim(), options)//  第二步优化,打上静态节点标记if (options.optimize !== false) {optimize(ast, options)}// 第三部步骤 - 生成代码字符串const code = generate(ast, options)return {ast,render: code.render,staticRenderFns: code.staticRenderFns}
})

 

  相关解决方案