xiaokeqi/i-learned

vue全家桶源码解析--参考于https://ustbhuangyi.github.io

xiaokeqi opened this issue · 4 comments

vue源码目录结构

vue源码均放在src目录下

  • compile 编译相关
  • core 核心代码
  • platforms 不同平台支持
  • server 服务端渲染
  • sfc 单文件.vue解析
  • shared 共享代码
    vue的源码构建是基于rullup的,其配置均放在scripts文件夹下

vue入口

vue入口文件在vue/src/core/instance/index.js下

import { initMixin } from './init'
import { stateMixin } from './state'
import { renderMixin } from './render'
import { eventsMixin } from './events'
import { lifecycleMixin } from './lifecycle'
import { warn } from '../util/index'

function Vue (options) {
  if (process.env.NODE_ENV !== 'production' &&
    !(this instanceof Vue)
  ) {
    warn('Vue is a constructor and should be called with the `new` keyword')
  }
  this._init(options)
}

initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)

export default Vue

源码如上,可见vue实质上是一个函数。我们使用时,只能通过new Vue来实例化使用它
函数声明vue后,调用mixin方法,将Vue传入,从而实现在Vue原型上挂载基本方法。
具体挂载的方法如下所示:
initMinin=>挂载 Vue.prototype._init方法

stateMixin=》挂载$data、$props、$set、$delete、$watch属性

  • Object.defineProperty(Vue.prototype, '$data', dataDef)
  • Object.defineProperty(Vue.prototype, '$props', propsDef)
  • Vue.prototype.$set = set
  • Vue.prototype.$delete = del
  • Vue.prototype.$watch

eventsMixin=>挂载$on、$once、$off、$emit方法

  • Vue.prototype.$emit
  • Vue.prototype.$off
  • Vue.prototype.$once
  • Vue.prototype.$on

lifecycleMixin => 挂载_update、$forceUpdate、$destroy

  • Vue.prototype._update
  • Vue.prototype.$forceUpdate
  • Vue.prototype.$destroy

renderMinxin =>挂载 $nextTick、_render

  • Vue.prototype.$nextTick
  • Vue.prototype._render

new Vue()

如上所示,new Vue()其主要调用了this._init(options)方法即原型链上Vue.prototype._init方法。_init方法在src/core/instance/init.js中,代码如下:

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

    let startTag, endTag
    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
      startTag = `vue-perf-start:${vm._uid}`
      endTag = `vue-perf-end:${vm._uid}`
      mark(startTag)
    }

    // a flag to avoid this being observed
    vm._isVue = true
    // merge options
    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
      )
    }
    /* istanbul ignore else */
    if (process.env.NODE_ENV !== 'production') {
      initProxy(vm)
    } else {
      vm._renderProxy = vm
    }
    // expose real self
    vm._self = vm
    initLifecycle(vm)
    initEvents(vm)
    initRender(vm)
    callHook(vm, 'beforeCreate')
    initInjections(vm) // resolve injections before data/props
    initState(vm)
    initProvide(vm) // resolve provide after data/props
    callHook(vm, 'created')

    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
      vm._name = formatComponentName(vm, false)
      mark(endTag)
      measure(`vue ${vm._name} init`, startTag, endTag)
    }

    if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
  }
}

可见,new Vue()主要执行了初始化操作,初始化生命周期、初始化事件、初始化渲染函数、插入beforeCreat钩子函数。初始化Injections、初始化State、初始化Provide,插入created钩子函数,最后执行挂载$mount函数

initLifecycle

initLifecycle存在于vue/src/core/instance/lifecycle.js文件中

export function initLifecycle (vm: Component) {
  const options = vm.$options
  
  // locate first non-abstract parent
  let parent = options.parent
  if (parent && !options.abstract) {
    while (parent.$options.abstract && parent.$parent) {
      parent = parent.$parent
    }
    parent.$children.push(vm)
  }

  vm.$parent = parent
  vm.$root = parent ? parent.$root : vm

  vm.$children = []
  vm.$refs = {}

  vm._watcher = null
  vm._inactive = null
  vm._directInactive = false
  vm._isMounted = false
  vm._isDestroyed = false
  vm._isBeingDestroyed = false
}

如代码所示,初始化声明周期,主要是关联了一下父子组件关系、其次初始化了声明周期状态

initEvents

export function initEvents (vm: Component) {
  vm._events = Object.create(null)
  vm._hasHookEvent = false
  // init parent attached events
  const listeners = vm.$options._parentListeners
  if (listeners) {
    updateComponentListeners(vm, listeners)
  }
}

初始化了一个空的事件对象。重名覆盖

initRender

export function initRender (vm: Component) {
  vm._vnode = null // the root of the child tree
  vm._staticTrees = null // v-once cached trees
  const options = vm.$options
  const parentVnode = vm.$vnode = options._parentVnode // the placeholder node in parent tree
  const renderContext = parentVnode && parentVnode.context
  vm.$slots = resolveSlots(options._renderChildren, renderContext)
  vm.$scopedSlots = emptyObject
  // bind the createElement fn to this instance
  // so that we get proper render context inside it.
  // args order: tag, data, children, normalizationType, alwaysNormalize
  // internal version is used by render functions compiled from templates
  vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
  // normalization is always applied for the public version, used in
  // user-written render functions.
  vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)

  // $attrs & $listeners are exposed for easier HOC creation.
  // they need to be reactive so that HOCs using them are always updated
  const parentData = parentVnode && parentVnode.data

  /* istanbul ignore else */
  if (process.env.NODE_ENV !== 'production') {
    defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, () => {
      !isUpdatingChildComponent && warn(`$attrs is readonly.`, vm)
    }, true)
    defineReactive(vm, '$listeners', options._parentListeners || emptyObject, () => {
      !isUpdatingChildComponent && warn(`$listeners is readonly.`, vm)
    }, true)
  } else {
    defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, null, true)
    defineReactive(vm, '$listeners', options._parentListeners || emptyObject, null, true)
  }
}

实例上挂载_c渲染函数、并将$attrs、$listenners中的属性值,变为响应式属性。