vue源码剖析1-初始化流程

初始化流程

vue初始化的流程是从new vue()开始的,在new vue()之后,会执行init,再 $mount实现挂载,在 $mount中执行mountComponent()的方法,执行挂载,获取vdom并转换为dom,mountComponent()方法包括后面的两个方法updataComponent()执行初始化并更新/new Watcher()创建组件渲染watcher =>update()初始化或更新,将传入vdom转换为dom,初始化时执行的是dom创建操作。
在这里插入图片描述
(图片摘自网络)

入口文件

入口:/web/entry-runtime-with-compiler.js
扩展默认$mount方法:处理template和el。附上代码,在代码中解释:

// 引入默认$mount方法,并扩展它
// 编译template
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  // 查询得到真实dom
  el = el && query(el)

  // 处理render或者template或者el三个选项
  // 编译并得到渲染函数
  /* istanbul ignore if */
  if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== 'production' && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )
    return this
  }

  const options = this.$options
  // resolve template/el and convert to render function

  //其实template和el最后都转化为render,并且三个的优先级为:
    // render > template > el
  if (!options.render) {  //先判断render
    let template = options.template
    if (template) {  //tempalte
      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) {
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile')
      }

      // 获取渲染函数
      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

      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile end')
        measure(`vue ${this._name} compile`, 'compile', 'compile end')
      }
    }
  }
  // 执行挂载
  return mount.call(this, el, hydrating)
}

我们在平时创建vue时会写成这样:

const app = new Vue({
  el: '#app',
})

但也可以写成这样:

const app = new Vue({
 render: h => h(App),
})

const app = new Vue({
 template: '<div>hhhh</div>',
})

安装web平台特有指令和组件

vue是支持移动端和web端的,都会有单独的文件设置,这里我们研究的是web端的。在文件web/runtime/index.js中,定义了_patch_:补丁函数和$mount方法。

$mount

// install platform patch function
// 安装平台补丁函数,
Vue.prototype.__patch__ = inBrowser ? patch : noop

// public mount method


Vue.prototype.$mount = function (
// el: 可以是一个字符串或者Dom元素
// hydrating 是Virtual DOM 的补丁算法参数
  el?: string | Element,
  hydrating?: boolean
): Component {
 // 判断el, 以及宿主环境, 然后通过工具函数query重写el。
  el = el && inBrowser ? query(el) : undefined
  // 实现mount方法:调用mountComponent
  return mountComponent(this, el, hydrating)
}

在这里面定义了__ patch __:补丁函数,执行patching算法进行更新 。(关于patch算法后面再详细更新)
定义 $ mount :挂载vue实例到宿主元素上,(获得dom并替换宿主元素)。
详细介绍一下$mount:

----$mount 方法支持传入 2 个参数,第一个是 el,它表示挂载的元素,可以是字符串,也可以是 DOM 对象,如果是字符串在浏览器环境下会调用 query 方法转换成 DOM 对象的。第二个参数是和服务端渲染相关,在浏览器环境下不需要传第二个参数。

mountComponent

在$mount 方法实中有调用 mountComponent 方法,方法定义在 src/core/instance/lifecycle.js 中:

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') {
    /* istanbul ignore if */
    if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
      vm.$options.el || el) {
      warn(
        'You are using the runtime-only build of Vue where the template ' +
        'compiler is not available. Either pre-compile the templates into ' +
        'render functions, or use the compiler-included build.',
        vm
      )
    } else {
      warn(
        'Failed to mount component: template or render function not defined.',
        vm
      )
    }
  }
}
callHook(vm, 'beforeMount')
let updateComponent
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
  updateComponent = () => {
    const name = vm._name
    const id = vm._uid
    const startTag = `vue-perf-start:${id}`
    const endTag = `vue-perf-end:${id}`

    mark(startTag)
    const vnode = vm._render()//先走_render函数把节点转化成vnode
    mark(endTag)
    measure(`vue ${name} render`, startTag, endTag)

    mark(startTag)
    vm._update(vnode, hydrating)  //将虚拟dom传给_update()
    mark(endTag)
    measure(`vue ${name} patch`, startTag, endTag)
  }
} else {
  updateComponent = () => {  //执行初始化并更新
    vm._update(vm._render(), hydrating)
  }
}

// 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
}

从上面的代码可以看到,mountComponent 核心就是先调用 vm._render 方法先生成模拟 Node,在实例化一个渲染 Watcher,在它的回调函数中会调用 updateComponent 方法,最终调用 vm._update 更新 DOM。

watcher 在这里起到两个作用,一个是初始化的时候会执行回调函数,另一个是当 vm 实例中的监测的数据发生变化的时候执行回调函数

定义全局API

在核心代码 core/index 中,引入了全局API的定义方法:

// 初始化全局API
initGlobalAPI(Vue)

在/core/global-api/index.js中查看到定义的全局的方法:

 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
}

vue构造函数的定义

在core/instance/index.js中,是vue的构造函数:

// Vue构造函数
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)
}

// 扩展Vue构造函数,实现多个”实例方法“"实例属性”
initMixin(Vue) // _init()
stateMixin(Vue) // $data/$set/$watch等等
eventsMixin(Vue) // $on/$off/...
lifecycleMixin(Vue) // $_update()/$destroy/...
renderMixin(Vue) // $nextTick / _render()

export default Vue

在vue的构造函数中,只有一步要紧的就是this._init(options),实现初始化,这个函数又是在哪里的呢?其实时候面initMixin(Vue)中的。再进入该函数中:
在文件/src/core/instance/init.js中

export function initMixin (Vue: Class<Component>) {
  // 对Vue扩展,实现_init实例方法
  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) // $parent/$children等等
    initEvents(vm) // 事件监听
    initRender(vm) // 插槽、_c...
    callHook(vm, 'beforeCreate')//生命周期钩子beforeCreate
    initInjections(vm) // resolve injections before data/props
    initState(vm) // 初始化data、prop、method并执行响应式
    initProvide(vm) // resolve provide after data/props
    callHook(vm, 'created') // 生命周期钩子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)
    }
  }
}

在最后的代码中,如果有el,实现挂载。

写在最后

如果大家发现有什么问题,可以留言,一起学习讨论。后面也会有脑图的更新。共勉。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值