Vue源码探秘(二)(从入口开始)

2020/3/19 11:02:32

本文主要是介绍Vue源码探秘(二)(从入口开始),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

引言

在上一篇文章中,我们大概了解了Vue.js的构建过程,在平时使用Vue时,要先使用new运算符调用Vue,也就是说Vue是一个构造函数。

本篇文章,我会从入口开始,带大家深入了解Vue 构造函数的真实模样以及它是如何初始化的。

Vue入口

在 web 应用下,我们来分析Runtime + Compiler构建出来的Vue.js,回顾上一节的vue.js源码构建部分,通过scripts目录下的config.jsalias.js,我们知道入口文件是/src/platforms/web/entry-runtime-with-compiler.js

打开入口文件:

// src/platforms/web/entry-runtime-with-compiler.js
/* @flow */

import config from 'core/config'
import { warn, cached } from 'core/util/index'
import { mark, measure } from 'core/util/perf'

import Vue from './runtime/index'
import { query } from './util/index'
import { compileToFunctions } from './compiler/index'
import { shouldDecodeNewlines, shouldDecodeNewlinesForHref } from './util/compat'

const idToTemplate = cached(id => {
  const el = query(id)
  return el && el.innerHTML
})

const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && query(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
  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) {
      /* 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)
}

/**
 * Get outerHTML of elements, taking care
 * of SVG elements in IE as well.
 */
function getOuterHTML (el: Element): string {
  if (el.outerHTML) {
    return el.outerHTML
  } else {
    const container = document.createElement('div')
    container.appendChild(el.cloneNode(true))
    return container.innerHTML
  }
}

Vue.compile = compileToFunctions

export default Vue

复制代码

可以看到这里引入了Vue又将其导出,所以入口文件并不是定义Vue函数的地方。

在这个入口文件中,主要做了两部分的工作:

  • 重写了Vue函数的原型上的$mount函数
  • 添加了全局函数compileToFunctions

继续往上找,我们看到引入Vue的地址是src/platforms/web/runtime/index.js。打开文件:

// src/platforms/web/runtime/index.js

/* @flow */

import Vue from 'core/index'
import config from 'core/config'
import { extend, noop } from 'shared/util'
import { mountComponent } from 'core/instance/lifecycle'
import { devtools, inBrowser } from 'core/util/index'

import {
  query,
  mustUseProp,
  isReservedTag,
  isReservedAttr,
  getTagNamespace,
  isUnknownElement
} from 'web/util/index'

import { patch } from './patch'
import platformDirectives from './directives/index'
import platformComponents from './components/index'

// install platform specific utils
Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isReservedAttr = isReservedAttr
Vue.config.getTagNamespace = getTagNamespace
Vue.config.isUnknownElement = isUnknownElement

// install platform runtime directives & components
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)

// install platform patch function
Vue.prototype.__patch__ = inBrowser ? patch : noop

// public mount method
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}

// devtools global hook
/* istanbul ignore next */
if (inBrowser) {
  setTimeout(() => {
    if (config.devtools) {
      if (devtools) {
        devtools.emit('init', Vue)
      } else if (
        process.env.NODE_ENV !== 'production' &&
        process.env.NODE_ENV !== 'test'
      ) {
        console[console.info ? 'info' : 'log'](
          'Download the Vue Devtools extension for a better development experience:\n' +
          'https://github.com/vuejs/vue-devtools'
        )
      }
    }
    if (process.env.NODE_ENV !== 'production' &&
      process.env.NODE_ENV !== 'test' &&
      config.productionTip !== false &&
      typeof console !== 'undefined'
    ) {
      console[console.info ? 'info' : 'log'](
        `You are running Vue in development mode.\n` +
        `Make sure to turn on production mode when deploying for production.\n` +
        `See more tips at https://vuejs.org/guide/deployment.html`
      )
    }
  }, 0)
}

export default Vue

复制代码

我们发现这里也不是定义Vue函数的地方,这里在Vue构造函数的原型上定义了$mount,同时往Vue.configVue.options上添加方法。继续往上找,我们看到它是从src/core/index.js引入的Vue

来到对应文件:

// src/core/index.js
import Vue from './instance/index'
import { initGlobalAPI } from './global-api/index'
import { isServerRendering } from 'core/util/env'
import { FunctionalRenderContext } from 'core/vdom/create-functional-component'

initGlobalAPI(Vue)

// ...
// 省略部分,下面回来详细分析

export default Vue

复制代码

很明显,这里也不是。继续往上走,来到src/core/instance/index.js:

// 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函数的地方了。

Vue的定义

找到了定义Vue的地方,它实际上是就是一个用Function实现的类,我们只能通过new Vue去实例化它。这块在函数体内也有体现。如果用户调用Vue的时候没有使用new操作符,就会抛出'Vue is a constructor and should be called with thenewkeyword'的警告。

之后调用了_init方法,并将这个构造函数作为参数传给了另外五个函数。我们先来看initMixin:

// src/core/instance/init.js
export function initMixin (Vue: Class<Component>) {
  Vue.prototype._init = function (options?: Object) {
    // ...
    // 省略中间代码逻辑
  }
}
复制代码

initMixin就是往Vue的原型上挂载刚刚提到的_init方法,大致就是内部的初始化过程。

其余四个函数也类似,都是往Vue.prototype上挂载属性和方法。

这里我们只是大致过下流程,上面五个函数内部具体进行了什么操作,我会在后面的文章中给大家分享、探秘。

看完Vue构造函数所在的src/core/instance/index.js文件,我们回到上一级,也就是src/core/index.js:

import Vue from './instance/index'
import { initGlobalAPI } from './global-api/index'
import { isServerRendering } from 'core/util/env'
import { FunctionalRenderContext } from 'core/vdom/create-functional-component'

initGlobalAPI(Vue)

Object.defineProperty(Vue.prototype, '$isServer', {
  get: isServerRendering
})

Object.defineProperty(Vue.prototype, '$ssrContext', {
  get () {
    /* istanbul ignore next */
    return this.$vnode && this.$vnode.ssrContext
  }
})

// expose FunctionalRenderContext for ssr runtime helper installation
Object.defineProperty(Vue, 'FunctionalRenderContext', {
  value: FunctionalRenderContext
})

Vue.version = '__VERSION__'

export default Vue

复制代码

这里调用了initGlobalAPI,参数为引入的构造函数Vue。之后又在Vue.prototype上添加了几个属性。下面我们一起来看下initGlobalAPI,这个函数在src/core/global-api/index.js中:

// src/core/global-api/index.js

/* @flow */

import config from '../config'
import { initUse } from './use'
import { initMixin } from './mixin'
import { initExtend } from './extend'
import { initAssetRegisters } from './assets'
import { set, del } from '../observer/index'
import { ASSET_TYPES } from 'shared/constants'
import builtInComponents from '../components/index'
import { observe } from 'core/observer/index'

import {
  warn,
  extend,
  nextTick,
  mergeOptions,
  defineReactive
} from '../util/index'

export function initGlobalAPI (Vue: GlobalAPI) {
  // config
  const configDef = {}
  configDef.get = () => config
  if (process.env.NODE_ENV !== 'production') {
    configDef.set = () => {
      warn(
        'Do not replace the Vue.config object, set individual fields instead.'
      )
    }
  }
  Object.defineProperty(Vue, 'config', configDef)

  // exposed util methods.
  // NOTE: these are not considered part of the public API - avoid relying on
  // them unless you are aware of the risk.
  Vue.util = {
    warn,
    extend,
    mergeOptions,
    defineReactive
  }

  Vue.set = set
  Vue.delete = del
  Vue.nextTick = nextTick

  // 2.6 explicit observable API
  Vue.observable = <T>(obj: T): T => {
    observe(obj)
    return obj
  }

  Vue.options = Object.create(null)
  ASSET_TYPES.forEach(type => {
    Vue.options[type + 's'] = Object.create(null)
  })

  // this is used to identify the "base" constructor to extend all plain-object
  // components with in Weex's multi-instance scenarios.
  Vue.options._base = Vue

  extend(Vue.options.components, builtInComponents)

  initUse(Vue)
  initMixin(Vue)
  initExtend(Vue)
  initAssetRegisters(Vue)
}

复制代码

Vue.js 在整个初始化过程中,除了给它的原型 prototype 上扩展方法,也给 Vue 这个对象本身扩展了全局的静态属性和方法。

这里先是创建了一个configDef用来代理Vue.config,在非生产环境下如果尝试修改config,会抛出警告'Do not replace the Vue.config object, set individual fields instead.'

下面又定义了util,留意这里的注释: NOTE: these are not considered part of the public API - avoid relying on them unless you are aware of the risk.也就是说 util 这个属性不是公共的 api,建议不要去依赖这个属性除非能够预知风险。

之后又在 Vue 上定义了多个属性和方法,然后调用 extend 方法,最后又将 Vue 作为参数传递给了这四个函数。

来看下这里的 extend 方法,定义在src/shared/util.js中:

// src/shared/util.js

/**
 * Mix properties into target object.
 */
export function extend (to: Object, _from: ?Object): Object {
  for (const key in _from) {
    to[key] = _from[key]
  }
  return to
}
复制代码

这个方法很简单,就是把builtInComponents的所有属性合并到Vue.options.components的对应属性上去。

而这里的builtInComponents来自于src/core/components/index.js:

// src/core/components/index.js
import KeepAlive from './keep-alive'

export default {
  KeepAlive
}

复制代码

其实也就是keep-alive组件。

总结

到这里,Vue整个的初始化过程也就介绍完毕了。整个过程就是定义Vue构造函数,然后它的原型 prototype 以及它本身都扩展了一系列的方法和属性。

Vue 构造函数全局的和原型上的属性和方法在本文没有细讲,这些属性和方法的原理和用途会放在Vue源码探秘系列的后面细细研究。也欢迎大家的持续关注!



这篇关于Vue源码探秘(二)(从入口开始)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程