你想要的——vue源码剖析(1)

背景

Vue.js是如今国内比较火的前端框架,愿望经由历程接下来的一系列文章,可以协助人人更好的相识Vue.js的完成道理。本次剖析的版本是Vue.js2.5.16。(延续更新中。。。)

目次

Vue.js的引入

这一章将会剖析用户在引入Vue.js后,Vue框架做的初始化事情:建立Vue这个类,并往Vue类上增加类属性&类要领和实例属性&实例要领。

流程图

《你想要的——vue源码剖析(1)》

流程剖析

1)进口文件(platforms/web/entry-runtime-with-compiler.js)

  • 引入 platforms/web/runtime/index.js 获得Vue类
  • 缓存Vue的原型链上增加$mount要领,并重写该要领

2)platforms/web/runtime/index.js

  • 引入 core/index.js 获得Vue类
  • 往Vue类的config属性上增加mustUseProp,isReservedTag,isReservedAttr,getTagNamespace,isUnknownElement
  • 扩大Vue类options属性的directives,components
  • 给Vue类增加实例要领__patch__,$mount

3)core/index.js

  • 引入core/instance/index.js获得Vue类
  • 为Vue类增加增加全局API
  • 设置Vue实例属性$isServer,$ssrContext
  • 设置Vue类属性 FunctionalRenderContext
  • 增加Vue类的版本号

4)core/instance/index.js

  • 声明Vue类
  • 将Vue类传入种种初始化要领initMixin,stateMixin,eventsMixin,lifecycleMixin,renderMixin

源码剖析:

我们将依据上述的流程剖析从后往前剖析,逐渐剖析Vue从定义到最后初始化完毕的全部流程。

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'

// 声明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类传入种种初始化要领

// 为Vue增加_init实例要领 Vue.prototype._init = function(){}
initMixin(Vue)

// 经由历程Object.defineProperty要领,增加vue的实例属性$data,$props,重要跟数据相干
// 增加Vue的实例要领 $set,$delete,$watch, eg:Vue.prototype.$set = function(){}
stateMixin(Vue)

// 增加Vue实例基本的事宜要领
// 增加Vue实例要领 $on, $off, $emit, $once  eg:Vue.prototype.$on = function () {}
eventsMixin(Vue)

// 增加Vue实例生命周期的要领,重要涉及到组件的更新与烧毁
// 增加Vue实例要领 $_update,$forceUpdate, $destroy
lifecycleMixin(Vue)

// 增加Vue实例要领 $nextTick, $_render以及_o,_n,_s,_l,_t等组件衬着相干的要领
renderMixin(Vue)

export default Vue

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'

// 为Vue增加类要领
// 经由历程Object.defineProperty要领增加Vue.config属性,
// 增加Vue.util,Vue.set,Vue.delelt,Vue.delete,Vue.nextTick,Vue.options
// 增加Vue.options上的'components','directives','filters'要领
// 完成Vue.options.components => 内建组件{keep-alive} => Vue.options.components.KeepAlive = xxxx
// 增加Vue.options上的_base属性
// 增加Vue.use,用于VUe插件的装置
// 增加Vue.mixin
// 增加Vue.extend,用于类的继续
// 增加Vue类上'component','directive','filter'要领

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

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, isChrome } 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'

// 完成Vue.config上的mustUseProp,isReservedTag,isReservedAttr,getTagNamespace,isUnknownElement要领
Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isReservedAttr = isReservedAttr
Vue.config.getTagNamespace = getTagNamespace
Vue.config.isUnknownElement = isUnknownElement

// 完成Vue.options上的directives,components要领
// Vue.options.directives的model,show
// Vue.options.components的Transition,TransitionGroup要领
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)

// install platform patch function
// Vue实例上的__patch__要领
Vue.prototype.__patch__ = inBrowser ? patch : noop

// public mount method
// Vue实例上的$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) {
        devtools.emit('init', Vue)
      } else if (
        process.env.NODE_ENV !== 'production' &&
        process.env.NODE_ENV !== 'test' &&
        isChrome
      ) {
        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

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'

// 完成经由历程id来缓存模板的功用。
const idToTemplate = cached(id => {
  const el = query(id)
  return el && el.innerHTML
})
// 缓存mount要领
const mount = Vue.prototype.$mount
// 从新完成Vue实例上的$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, {
        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要领
Vue.compile = compileToFunctions

export default Vue

以上就是引入Vue.js以后全部初始化历程。

    原文作者:Daniel_Cheung
    原文地址: https://segmentfault.com/a/1190000014118553
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞