你想要的——vue源碼分析(1)

背景

Vue.js是如今國內比較火的前端框架,但願經過接下來的一系列文章,可以幫助你們更好的瞭解Vue.js的實現原理。本次分析的版本是Vue.js2.5.16。(持續更新中。。。)html

目錄

Vue.js的引入

這一章將會分析用戶在引入Vue.js後,Vue框架作的初始化工做:建立Vue這個類,並往Vue類上添加類屬性&類方法和實例屬性&實例方法。前端

流程圖vue

圖片描述

流程分析node

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

  • 引入 platforms/web/runtime/index.js 獲得Vue類
  • 緩存Vue的原型鏈上添加$mount方法,並重寫該方法

2)platforms/web/runtime/index.jsgithub

  • 引入 core/index.js 獲得Vue類
  • 往Vue類的config屬性上添加mustUseProp,isReservedTag,isReservedAttr,getTagNamespace,isUnknownElement
  • 擴展Vue類options屬性的directives,components
  • 給Vue類添加實例方法__patch__,$mount

3)core/index.jsweb

  • 引入core/instance/index.js獲得Vue類
  • 爲Vue類添加添加全局API
  • 設置Vue實例屬性$isServer,$ssrContext
  • 設置Vue類屬性 FunctionalRenderContext
  • 添加Vue類的版本號

4)core/instance/index.jssegmentfault

  • 聲明Vue類
  • 將Vue類傳入各類初始化方法initMixin,stateMixin,eventsMixin,lifecycleMixin,renderMixin

源碼分析:api

咱們將根據上述的流程分析從後往前分析,逐步分析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以後整個初始化過程。

相關文章
相關標籤/搜索