vue源码阅读(一)

版本:2.5.17-beta.0

核心模块(src/core):包括组件、全局API、vue实例、对象属性监测系统、公共方法、虚拟dom、配置等模块

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'
//添加全局api
initGlobalAPI(Vue)
//服务端 运行判断
Object.defineProperty(Vue.prototype, '$isServer', {
  get: isServerRendering
})
//处理内存泄漏 处理
Object.defineProperty(Vue.prototype, '$ssrContext', {
  get () {
    /* istanbul ignore next */
    return this.$vnode && this.$vnode.ssrContext
  }
})
// 不知道干啥的todo
Object.defineProperty(Vue, 'FunctionalRenderContext', {
  value: FunctionalRenderContext
})
//__VERSION__是配置的变量
Vue.version = '__VERSION__'
export default Vue

 

突然发现源码 读起来还好 写出来怎么那么麻烦啊!

initGlobalApi

/* @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 {
  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.

  //在这个地方挂载 util方法
  Vue.util = {
    warn,
    extend,
    mergeOptions,  //合并options.js
    defineReactive   //
  }
  Vue.set = set
  Vue.delete = del

  //方法来自 "../util/index"
  Vue.nextTick = nextTick

  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

  //keep-alive 组件,点进去就可以看到
  extend(Vue.options.components, builtInComponents)

  //Vue.use()方法
  initUse(Vue)

  //Vue.mixin()方法
  initMixin(Vue)

  //Vue.extend() 方法
  initExtend(Vue)

  //Vue.component, Vue.directive, Vue.filter
  initAssetRegisters(Vue)
}

util 方法 extend,mergeOptions,defineReactive,nextTick 

extend 

/**
 * 简单的对象的浅拷贝,有点失望
 */
export function extend (to: Object, _from: ?Object): Object {
  for (const key in _from) {
    to[key] = _from[key]
  }
  return to
}

 

 写出来真麻烦

posted @ 2018-06-11 16:21  雨中伞  阅读(351)  评论(0编辑  收藏  举报