前端养成

Vue 和 Vue.prototype是怎么一步一步“丰富”起来

2021-06-23  本文已影响0人  云海成长

vue 可以运行在 web 平台和 weex 平台,以 web 平台为例,从它的入口文件开始:

web平台入口文件
一看,怎么有好几个,它们的区别具体可参考:https://cn.vuejs.org/v2/guide/installation.html#%E5%AF%B9%E4%B8%8D%E5%90%8C%E6%9E%84%E5%BB%BA%E7%89%88%E6%9C%AC%E7%9A%84%E8%A7%A3%E9%87%8A,我们这里不做赘述。

选择其中一个入口src\platforms\web\entry-runtime-with-compiler.js
我们重点关注Vue的变化,查看源码可知

那么,为了弄清楚我们的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)
}
// 在执行以下操作之前,Vue就是一个非常普通的构造函数,Vue.prototype像这样:{constructor: ƒ}
initMixin(Vue)  // 这里在Vue.prototype挂载_init
stateMixin(Vue) // 这里在Vue.prototype挂载$prop, $data, $watch, $set, $delete
eventsMixin(Vue) // 这里在Vue.prototype挂载了事件相关的$on, $once, $off, $emit
lifecycleMixin(Vue) // 这里在Vue.prototype挂载了_update,$forceUpdate,$destroy生命周期相关的
renderMixin(Vue)
/**
 *  这一步Vue.prototype上主要关注挂载了$nextTick, _render
 *  其他:挂载了渲染相关的工具,以_开头,
 *  _b: ƒ bindObjectProps( data, tag, value, asProp, isSync )
 *  _d: ƒ bindDynamicKeys(baseObj, values)
 *  _e: ƒ (text)
 *  _f: ƒ resolveFilter(id)
 *  _g: ƒ bindObjectListeners(data, value)
 *  _i: ƒ looseIndexOf(arr, val)
 *  _init: ƒ (options)
 *  _k: ƒ checkKeyCodes( eventKeyCode, key, builtInKeyCode, eventKeyName, builtInKeyName )
 *  _l: ƒ renderList( val, render )
 *  _m: ƒ renderStatic( index, isInFor )
 *  _n: ƒ toNumber(val)
 *  _o: ƒ markOnce( tree, index, key )
 *  _p: ƒ prependModifier(value, symbol)
 *  _q: ƒ looseEqual(a, b)
* /

export default Vue

经过上面的步骤,Vue 的原型变成:


Vue.prototype

于是我们开始查看第二个文件src\core\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), 于是我们重点关注这个方法

initGlobalAPI(Vue)

位置: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) // 这一步在Vue上(注意不是Vue.prototype)挂载了静态属性config

  // 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) // Vue上挂载use
  initMixin(Vue) // Vue上挂载mixin
  initExtend(Vue) // Vue上挂载extend
  initAssetRegisters(Vue) // vue上挂载directives,filters,components
}

initGlobalAPI 对 Vue 做了什么?

  1. 在 Vue 上挂载config属性,即

    Vue.config
  2. 在 Vue 上挂载了util, set, delete, nextTick, observable, use, mixin, extend, cid, directives, filters, components方法

    Vue.xxx
    Vue.xxx
  3. 在 Vue 上挂载了 options, options 的值即

    Vue.options(跟Vue的静态属性部分重合)
    另外,options._base = Vue

initGlobalAPI 的分析到此为止, 接下来看src\core\index.js还做了哪些事情?

接下来我们分析第3个文件。

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进行扩展
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
// 扩展Vue.options.directives和Vue.options.components
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)

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

// public mount method
// Vue.prototype挂载$mount方法
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) { // 使用Vue开发工具插件
        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.config的扩展,在Vue.proptotype上挂载了$mount_patch_方法。

分析最后一个文件

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
})
// mount 缓存原理的$mount方法
const mount = Vue.prototype.$mount
// 重写$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
  }
}
// 挂载编译器compile
Vue.compile = compileToFunctions
export default Vue

上面其实也就做了3件事情

  1. 缓存原来的$mount方法(因为后面$mount会被重写且使用到)
  2. 重写Vue.prototype上的$mount方法
  3. 在Vue上挂载compile

结果

经过上面的步骤,VueVue.prototype的结果如下

结果
上一篇下一篇

猜你喜欢

热点阅读