关于javascript:vue源码解析开始

61次阅读

共计 6590 个字符,预计需要花费 17 分钟才能阅读完成。

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

一. 模块概览

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 的主入口文件啦~

三. 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 的庐山真面目,它其实就是个构造函数。

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,&dollar;destory,&dollar;data,&dollar;props,&dollar;forceUpdate 等。
  • 对_data, _props 应用 Object.defineProperty 增加响应式
  • 设置拜访数据代理,拜访 this.xx,实际上拜访的是 vm._data[xx], vm._props[xx]
  • 增加 event 事件零碎,实际上初始化的是父组件在模板中应用 v -on 或 @注册的监听子组件内触发的事件
  • 挂载 createElement,为后续 render 返回虚构 DOM 做筹备。
  • 调用对应的组件生命周期钩子,beforeCreate, created

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

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

正文完
 0