Vue源码解析-开始__Vue.js
发布于 3 年前 作者 banyungong 1024 次浏览 来自 分享
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利

主题列表:juejin, github, smartblue, cyanosis, channing-cyan, fancy, hydrogen, condensed-night-purple, greenwillow, v-green, vue-pro, healer-readable, mk-cute, jzman, geek-black, awesome-green, qklhk-chocolate

贡献主题:https://github.com/xitu/juejin-markdown-themes

theme: juejin highlight:

vue.js 是一套构建用户界面的渐进式框架,其轻量,易学受到许多开发者的喜爱。了解源码,有助于我们深刻理解vue。 知其然知其所以然,是每个工程师进阶的必经之路。话不多说,进入主题。

image.png

一. 模块概览

vue的源码主要分6个大模块

模块名 说明
compiler 编译相关
core vue核心代码
platforms 平台,目前是web和weex
server 服务端渲染
sfc .vue文件解析
shared 共享代码

二. 主入口分析

vue使用rollup做为打包工具,我首先查看package.json中的scripts。

package.json

"scripts": {
    "dev": "rollup -w -c scripts/config.js --environment TARGET:web-full-dev",
    "dev:cjs": "rollup -w -c scripts/config.js --environment TARGET:web-runtime-cjs-dev",
    "dev:esm": "rollup -w -c scripts/config.js --environment TARGET:web-runtime-esm",
    "dev:test": "karma start test/unit/karma.dev.config.js",
    "dev:ssr": "rollup -w -c scripts/config.js --environment TARGET:web-server-renderer",
    "dev:compiler": "rollup -w -c scripts/config.js --environment TARGET:web-compiler ",
    "dev:weex": "rollup -w -c scripts/config.js --environment TARGET:weex-framework",
    "dev:weex:factory": "rollup -w -c scripts/config.js --environment TARGET:weex-factory",
    "dev:weex:compiler": "rollup -w -c scripts/config.js --environment TARGET:weex-compiler ",
    "build": "node scripts/build.js",
    "build:ssr": "npm run build -- web-runtime-cjs,web-server-renderer",
    "build:weex": "npm run build -- weex",
    "test": "npm run lint && flow check && npm run test:types && npm run test:cover && npm run test:e2e -- --env phantomjs && npm run test:ssr && npm run test:weex",
    "test:unit": "karma start test/unit/karma.unit.config.js",
    "test:cover": "karma start test/unit/karma.cover.config.js",
    "test:e2e": "npm run build -- web-full-prod,web-server-basic-renderer && node test/e2e/runner.js",
    "test:weex": "npm run build:weex && jasmine JASMINE_CONFIG_PATH=test/weex/jasmine.js",
    "test:ssr": "npm run build:ssr && jasmine JASMINE_CONFIG_PATH=test/ssr/jasmine.js",
    "test:sauce": "npm run sauce -- 0 && npm run sauce -- 1 && npm run sauce -- 2",
    "test:types": "tsc -p ./types/test/tsconfig.json",
    "lint": "eslint src scripts test",
    "flow": "flow check",
    "sauce": "karma start test/unit/karma.sauce.config.js",
    "bench:ssr": "npm run build:ssr && node benchmarks/ssr/renderToString.js && node benchmarks/ssr/renderToStream.js",
    "release": "bash scripts/release.sh",
    "release:weex": "bash scripts/release-weex.sh",
    "release:note": "node scripts/gen-release-note.js",
    "commit": "git-cz"
  },

我们主要看build命令: node scripts/build.js

scripts/build.js 主干代码如下:

let builds = require('./config').getAllBuilds();
// 此处省略n行
build(builds)

根据config.js获取到getAllBuilds方法,这里我们看 runtime + compiler 版本

说明下,vue的compiler分两种情况(web端):

  • 使用vue-loader在构建时compiler,简称:构建时compiler。
  • 在vue运行时,再去compiler,简称:运行时compiler。

这里,我们考虑全版的vue源代码,选择runtime + 运行时compiler 版本

// Runtime+compiler ES modules build (for direct import in browser)
  'web-full-esm-browser-prod': {
    entry: resolve('web/entry-runtime-with-compiler.js'),
    dest: resolve('dist/vue.esm.browser.min.js'),
    format: 'es',
    transpile: false,
    env: 'production',
    alias: { he: './entity-decoder' },
    banner
  },

到这里,我们已找到vue的主入口文件啦~

image.png

三. Vue真面目是个啥

我们进入entry-runtime-with-compiler.js主文件,先分析主干,抛开分支:

// ...
import Vue from './runtime/index'
import { compileToFunctions } from './compiler/index'
// ...
Vue.prototype.$mount = function () {
 // ...
}
Vue.compile = compileToFunctions

export default Vue

runtime/index

我们进入runtime/index.js,继续寻找vue

import Vue from 'core/index'
// ...
export default Vue

core/index

import Vue from './instance/index'
import { initGlobalAPI } from './global-api/index'
// ...
initGlobalAPI(Vue)
// ...
export default Vue

instance/index

到这里,我们终于看到Vue的庐山真面目,它其实就是个构造函数。

image.png

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)
}

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

export default Vue

到这里,我们已经看到,vue.js加载完成后,初始化了5个方法,分别是initMixin, stateMixin, eventsMixin, lifecycleMixin, renderMixin。 下面,我们来逐个击破。

四. initMixin

 Vue.prototype._init = function (options?: Object) {
  const vm: Component = this
  // ...
}

vue在此方法中声明了_init方法。 这实际上就是我们使用vue时, new Vue(options),实例化vue时执行的方法。

此方法核心流程如下:

1. 合并options配置,并挂载至 vm.$options上

2. initLifecycle

初始化vm.$parent, vm.$root, vm.$children, vm.$refs 等属性值

3. initEvents

初始化vm._events={},初始化事件系统 实际上是父组件在模板中使用v-on或@注册的监听子组件内触发的事件

4. initRender

主要定义2个方法:

  • vm._c,此方法用于用户使用template模式
  • vm.$createElement,此方法用于用户手写render函数

这2个方法,最终都会调用createElement方法,createElement方法将在虚拟DOM章节重点分析,这里我们只需知道,此方法返回虚拟DOM

5. 调用 beforeCreate 钩子

6. initInjections

此方法,里面的inject和provide是成对出现的。作用是父组件提供数据,任意嵌套层级的子组件可以去接受。其中provide是数据提供方,inject是数据接受方。

7. initState

  • 初始化state, props, methods, computed, watch
  • 其中初始化state, props, methods时, vue会遍历data中所有的key,检测是否在props,methods重复定义
  • props变量有多种写法,vue会进行统一转化,转化成{ a: {type: “xx”, default: ‘xx’} }
  • 将data, props都挂载到vm._data, vm._props上。设置访问数据代理,访问this.xx,实际上访问的是vm._data[xx], vm._props[xx]
  • 给_data, _props添加响应式监听

8. initProvide

同initInjections

9. 调用 created 钩子

五. stateMixin

  • 定义Vue.prototype.$data, Vue.prototype.$props为响应式。
  • 获取vm.$data实际上是获取vm._data, vm.$props实际上是vm._props
  • 定义Vue.prototype.$watch方法,实际上是实例化Watcher类

六. eventsMixin

  • 在Vue原型上,定义$on, $once, $off, $emit 事件方法,并返回vm

七. lifecycleMixin

  • 在Vue.prototype上定义 _update, $forceUpdate, $destroy方法

八. renderMixin

  • 在Vue原型上,定义$nextTick方法
  • 在Vue原型上,定义_render方法,值得注意的是,该方法会调用vm.$createElement创建虚拟DOM,如果返回值vnode不是虚拟DOM类型,将创建一个空的虚拟DOM。 虚拟DOM:VNode,实际上是一个类,结构大致如下:
class VNode {
  tag: string | void;
  data: VNodeData | void;
  children: ?Array<VNode>;
  text: string | void;
  elm: Node | void;
  ns: string | void;
  context: Component | void; 
  key: string | number | void;
  componentOptions: VNodeComponentOptions | void;
  componentInstance: Component | void;
  parent: VNode | void; 

  // ...更多属性,可以暂时不关注
}

createElement方法最终创建VNode,相关6个参数如下:

参数名 说明
context: Component vue实例对象
tag: any 标签名,可以是个string div,也可以是一个组件标签
data: VNodeData 见下面interface VNodeData
children: Array<VNode> 嵌套div等结构
normalizationType: any 标记,1 simple 2 always
alwaysNormalize: any 判断是否是always true是

VNodeData数据结构:

interface VNodeData {
  key?: string | number;
  slot?: string;
  scopedSlots?: { [key: string]: ScopedSlot | undefined };
  ref?: string;
  refInFor?: boolean;
  tag?: string;
  staticClass?: string;
  class?: any;
  staticStyle?: { [key: string]: any };
  style?: string | object[] | object;
  props?: { [key: string]: any };
  attrs?: { [key: string]: any };
  domProps?: { [key: string]: any };
  hook?: { [key: string]: Function };
  on?: { [key: string]: Function | Function[] };
  nativeOn?: { [key: string]: Function | Function[] };
  transition?: object;
  show?: boolean;
  inlineTemplate?: {
    render: Function;
    staticRenderFns: Function[];
  };
  directives?: VNodeDirective[];
  keepAlive?: boolean;
}

九. 总结

  • Vue本质上,是一个构造函数。
  • 初始化了:state, props, methods, computed, watch,$destory,$data,$props,$forceUpdate等。
  • 对_data, _props使用 Object.defineProperty 添加响应式
  • 设置访问数据代理,访问this.xx,实际上访问的是vm._data[xx], vm._props[xx]
  • 添加event事件系统,实际上初始化的是父组件在模板中使用v-on或@注册的监听子组件内触发的事件
  • 挂载createElement,为后续render返回虚拟DOM做准备。
  • 调用对应的组件生命周期钩子, beforeCreate, created

下一章,我们将详细分析:vue中数据变化监听

码字不易,多多关注,点赞~😽

版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 作者: 老刘大话前端 原文链接:https://juejin.im/post/6931931603593592846

回到顶部