# vue2源码

src
├── compiler        # 编译相关 
├── core            # 核心代码 
├── platforms       # 不同平台的支持: web 和 weex 
├── server          # 服务端渲染
├── sfc             # .vue 文件解析: .vue 文件内容解析成一个 JavaScript 的对象
├── shared          # 共享代码:浏览器端的 Vue.js 和服务端的 Vue.js 所共享的

# 入口文件platforms/web/entry-runtime-with-compiler.js

作用:扩展默认$mount方法:处理template或el选项 render>template>el

const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && query(el)

  const options = this.$options
  // resolve template/el and convert to render function
  if (!options.render) {
    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)
    }
    if (template) {
      const { render, staticRenderFns } = compileToFunctions(template, {
        outputSourceRange: process.env.NODE_ENV !== 'production',
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      options.render = render
      options.staticRenderFns = staticRenderFns
    }
  }
  return mount.call(this, el, hydrating)
}

# platforms/web/runtime/index.js

  1. 安装补丁函数,vdom=>dom
Vue.prototype.__patch__ = inBrowser ? patch : noop
  1. 实现$mount方法,挂载vue实例到指定宿主元素(获得dom并替换宿主元素):调用mountComponent,vdom=>dom=>append
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}
$mount
- mountComponent
执行挂载,获取vdom并转换为dom
 
- new Watcher() 
创建组件渲染watcher
 
- updateComponent()
执行初始化或更新
       
- update()
初始化或更新,将传入vdom转换为dom,初始化时执行的是dom创建操作
 
- render()  src\core\instance\render.js
渲染组件,获取vdom

# core/index.js

初始化全局api

Vue.set = set 
Vue.delete = del 
Vue.nextTick = nextTick
initUse(Vue) // 实现Vue.use函数 
initMixin(Vue) // 实现Vue.mixin函数 
initExtend(Vue) // 实现Vue.extend函数 
initAssetRegisters(Vue) // 注册实现Vue.component/directive/filter

# core/instance/index.js

Vue构造函数定义,定义Vue实例API

function Vue (options) {
// 构造函数仅执行了_init
	this._init(options) 	
}
initMixin(Vue) // 实现init函数 
stateMixin(Vue) // 状态相关api $data,$props,$set,$delete,$watch 
eventsMixin(Vue)// 事件相关api $on,$once,$off,$emit 
lifecycleMixin(Vue) // 生命周期api _update,$forceUpdate,$destroy 
renderMixin(Vue)// 渲染api _render,$nextTick

# core/instance/init.js

创建组件实例,初始化其数据、属性、事件等,如果设置了el,则自动执行$mount()

export function initMixin (Vue: Class<Component>) {
  // 原型方法 vm._init
  Vue.prototype._init = function (options?: Object) {
    const vm: Component = this
    // a uid
    vm._uid = uid++

    let startTag, endTag
    /* istanbul ignore if */
    // a flag to avoid this being observed
    vm._isVue = true
    // merge options
    // 合并选项:new Vue时传入的是用户配置选项,它们需要和系统配置合并
    if (options && options._isComponent) {
      // optimize internal component instantiation
      // since dynamic options merging is pretty slow, and none of the
      // internal component options needs special treatment.
      initInternalComponent(vm, options)
    } else {
      vm.$options = mergeOptions(
        resolveConstructorOptions(vm.constructor),
        options || {},
        vm
      )
    }
    vm._self = vm
    initLifecycle(vm) // 实例属性:$parent,$root,$children,$refs
    initEvents(vm) // 自定义事件处理
    initRender(vm) // 插槽解析,$slots,$scopeSlots,  $createElement()
    callHook(vm, 'beforeCreate')
    // 接下来都是和组件状态相关的数据操作
    // inject/provide
    initInjections(vm) // 注入祖辈传递下来的数据
    initState(vm) // 数据响应式:props,methods,data,computed,watch
    initProvide(vm) // 提供给后代,用来隔代传递参数
    callHook(vm, 'created')

    // 如果设置了el,则自动执行$mount()
    if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
  }
}

# core/observer/index.js

Observer对象根据数据类型执行对应的响应化操作 defineReactive定义对象属性的getter/setter,getter负责添加依赖,setter负责通知更新

# core/observer/dep.js

Dep负责管理一组Watcher,包括watcher实例的增删及通知更新

# watcher

Watcher解析一个表达式并收集依赖,当数值变化时触发回调函数,常用于$watch API和指令中。每个组件也会有对应的Watcher,数值变化会触发其update函数导致重新渲染

export default class Watcher {
constructor () {}
  get () {}
  addDep (dep: Dep) {}
  update () {}
}

相关API: $watcher

# new Vue做的事情

初始化 => 根实例 => 挂载($mount) => 执行render => vdom => patch(vdom) => dom =>append

手写vue

# vue源码

从github上下载源码

yarn安装依赖,同时由于vue2使用了rollup打包,要全局安装grollup

npm i rollup -g

完成后可以开启npm run dev进行修改源码,查看效果,需要给package.json中的命令行dev中加上--sourcemap

参考资料 (opens new window)

最后更新: 10/18/2021, 7:29:44 PM