美文网首页
vue 源码 - 03 vue核心定义

vue 源码 - 03 vue核心定义

作者: Lisa_Guo | 来源:发表于2019-12-27 11:39 被阅读0次

有关vue的核心定义都在src/core下, 目录结构如下

├─ core                    // Vue核心代码,包括内置组件,全局API封装,Vue 实例化,观察者,虚拟DOM, 工具函数等等。
    ├─ components          // 组件相关属性
    ├─ global-api          // Vue全局API,如Vue.use,Vue.extend,Vue.mixin等
    ├─ instance            // Vue的基础类定义
          ├─ event.js         // 事件相关函数
          ├─ init.js          // 定义vue的init方法 
          ├─ lifecycle.js     // 生命周期相关函数
          ├─ proxy.js
          ├─ render.js        // 渲染相关函数
          ├─ state.js         // 与数据相关的函数,data、props、计算属性、watch等
    ├─ observer            // 响应式核心目录,双向数据绑定相关文件
    ├─ util                // 工具方法
    ├─ vdom                // 包含虚拟DOM 创建(creation)和打补丁(patching) 的代码
    ├─ config.js            //  Vue的全局配置
    ├─ index.js             // core入口文件,输出vue的核心定义

src/core/index.js引入vue实体定义后,进行全局配置等定制操作。其代码结构如下图

import Vue from './instance/index'
import { initGlobalAPI } from './global-api/index'
...
initGlobalAPI(Vue)
// other property definition
...

export default Vue

src/core/global-api/index.js定义vue的全局API

...
export function initGlobalAPI(Vue) {
    // 全局配置
    const configDef = {}
    configDef.get = () => config
    Object.defineProperty(Vue, 'config', configDef)

   // 定义全局函数: util,set,delete, nextTick,observable
   Vue.util = { warn, extend, mergeOptions, defineReactive }
   Vue.set = set
   Vue.delete = del
   Vue.nextTick = nextTick
   Vue.observable = <T>(obj: T): T => {
     observe(obj)
     return obj
   }

   // 定义全局options
   // ASSET_TYPES = ["component", "directive", "filter"]
   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

   // 加载内部components
   extend(Vue.options.components, builtInComponents)

   // 定义全局函数:use,mixin,extend,component,directive,filter
   initUse(Vue)
   initMixin(Vue)
   initExtend(Vue)
   initAssetRegisters(Vue)  // 定义 component, directive, filter全局函数
}
F12查看vue全局属性

/src/core/instance/index.js定义vue:

  1. 接受options为参数,其类型为对象。具体参见 vue api选项部分
  2. new Vue生成实例时会自动调用this._init进行初始化

其代码主体如下:

function Vue (options) {
  ...
  this._init(options)
}

initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)

export default Vue
F12查看Vue的原型定义

整体逻辑结构如下图


vue instance.png

相关文章

网友评论

      本文标题:vue 源码 - 03 vue核心定义

      本文链接:https://www.haomeiwen.com/subject/wvjloctx.html