Vue框架中的基本原理可能你们都基本了解了,可是尚未漫游一下源码。 因此,以为仍是有必要跑一下。 因为是代码漫游,因此大部分为关键性代码,以主线路和主要分支的代码为主,大部分理解都写在代码注释中。
文件结构1-->4,代码执行顺序4-->1html
web不一样平台入口;vue
/* @flow */ import Vue from './runtime/index' export default Vue
为Vue配置一些属性方法node
/* @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' // install platform specific utils Vue.config.mustUseProp = mustUseProp Vue.config.isReservedTag = isReservedTag Vue.config.isReservedAttr = isReservedAttr Vue.config.getTagNamespace = getTagNamespace Vue.config.isUnknownElement = isUnknownElement // install platform runtime directives & components extend(Vue.options.directives, platformDirectives) extend(Vue.options.components, platformComponents) // install platform patch function Vue.prototype.__patch__ = inBrowser ? patch : noop // public mount method 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 */ Vue.nextTick(() => { if (config.devtools) { if (devtools) { devtools.emit('init', Vue) } else if (process.env.NODE_ENV !== 'production' && 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' && config.productionTip !== false && inBrowser && 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
/* @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,建立了一个configDef对象,最终目的是为了Object.defineProperty(Vue, 'config', configDef) 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) // 具体Vue.congfig的具体内容就要看../config文件了 // exposed util methods. // NOTE: these are not considered part of the public API - avoid relying on them unless you are aware of the risk. // 添加一些方法,可是该方法并非公共API的一部分。源码中引入了flow.js Vue.util = { warn, // 查看'../util/debug' extend,//查看'../sharde/util' mergeOptions,//查看'../util/options' defineReactive//查看'../observe/index' } Vue.set = set //查看'../observe/index' Vue.delete = del//查看'../observe/index' Vue.nextTick = nextTick//查看'../util/next-click'.在callbacks中注册回调函数 // 建立一个纯净的options对象,添加components、directives、filters属性 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/keep-alive.js 拷贝组件对象。该部分最重要的一部分。 extend(Vue.options.components, builtInComponents) // Vue.options = { // components : { // KeepAlive : { // name : 'keep-alive', // abstract : true, // created : function created(){}, // destoryed : function destoryed(){}, // props : { // exclude : [String, RegExp, Array], // includen : [String, RegExp, Array], // max : [String, Number] // }, // render : function render(){}, // watch : { // exclude : function exclude(){}, // includen : function includen(){}, // } // }, // directives : {}, // filters : {}, // _base : Vue // } // } // 添加Vue.use方法,使用插件,内部维护一个插件列表_installedPlugins,若是插件有install方法就执行本身的install方法,不然若是plugin是一个function就执行这个方法,传参(this, args) initUse(Vue) // ./mixin.js 添加Vue.mixin方法,this.options = mergeOptions(this.options, mixin), initMixin(Vue) // ./extend.js 添加Vue.cid(每个够着函数实例都有一个cid,方便缓存),Vue.extend(options)方法 initExtend(Vue) // ./assets.js 建立收集方法Vue[type] = function (id: string, definition: Function | Object),其中type : component / directive / filter initAssetRegisters(Vue) }
Vue.util对象的部分解释:react
Vue.util.warn
warn(msg, vm) 警告方法代码在util/debug.js,
经过var trac = generateComponentTrace(vm)方法vm=vm.$parent递归收集到msg出处。
而后判断是否存在console对象,若是有 console.error([Vue warn]: ${msg}${trace}
)。
若是config.warnHandle存在config.warnHandler.call(null, msg, vm, trace)ios
Vue.util.extendgit
extend (to: Object, _from: ?Object):Object Object类型浅拷贝方法代码在shared/util.js
Vue.util.mergeOptionsgithub
合并,vue实例化和实现继承的核心方法,代码在shared/options.js mergeOptions ( parent: Object, child: Object, vm?: Component ) 先经过normalizeProps、normalizeInject、normalizeDirectives以Object-base标准化,而后依据strats合并策略进行合并。 strats是对data、props、watch、methods等实例化参数的合并策略。除此以外还有defaultStrat默认策略。 后期暴露的mixin和Vue.extend()就是从这里出来的。[官网解释][1]
Vue.util.defineReactiveweb
你们都知道的数据劫持核心方法,代码在shared/util.js defineReactive ( obj: Object, key: string, val: any, customSetter?: ?Function, shallow?: boolean )
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) { // 判断是不是new调用。 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._init(options)内部方法,./init.js initMixin(Vue) /** * ./state.js * 添加属性和方法 * Vue.prototype.$data * Vue.prototype.$props * Vue.prototype.$watch * Vue.prototype.$set * Vue.prototype.$delete */ stateMixin(Vue) /** * ./event.js * 添加实例事件 * Vue.prototype.$on * Vue.prototype.$once * Vue.prototype.$off * Vue.prototype.$emit */ eventsMixin(Vue) /** * ./lifecycle.js * 添加实例生命周期方法 * Vue.prototype._update * Vue.prototype.$forceUpdate * Vue.prototype.$destroy */ lifecycleMixin(Vue) /** * ./render.js * 添加实例渲染方法 * 经过执行installRenderHelpers(Vue.prototype);为实例添加不少helper * Vue.prototype.$nextTick * Vue.prototype._render */ renderMixin(Vue) export default Vue
初始化,完成主组件的全部动做的主线。从这儿出发能够理清observer、watcher、compiler 、render等express
import config from '../config' import { initProxy } from './proxy' import { initState } from './state' import { initRender } from './render' import { initEvents } from './events' import { mark, measure } from '../util/perf' import { initLifecycle, callHook } from './lifecycle' import { initProvide, initInjections } from './inject' import { extend, mergeOptions, formatComponentName } from '../util/index' let uid = 0 export function initMixin (Vue: Class<Component>) { Vue.prototype._init = function (options?: Object) { const vm: Component = this // a uid vm._uid = uid++ let startTag, endTag /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { startTag = `vue-perf-start:${vm._uid}` endTag = `vue-perf-end:${vm._uid}` mark(startTag) } // a flag to avoid this being observed vm._isVue = true // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options) } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ) } /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { initProxy(vm) } else { vm._renderProxy = vm } // expose real self vm._self = vm initLifecycle(vm) initEvents(vm) /** * 添加vm.$createElement vm.$vnode vm.$slots vm. * 建立vm.$attrs / vm.$listeners 而且转换为getter和setter * */ initRender(vm) callHook(vm, 'beforeCreate') initInjections(vm) // resolve injections before data/props vm.$scopedSlots /** * 一、建立 vm._watchers = []; * 二、执行if (opts.props) { initProps(vm, opts.props); } 验证props后调用defineReactive转化,而且代理数据proxy(vm, "_props", key); * 三、执行if (opts.methods) { initMethods(vm, opts.methods); } 而后vm[key] = methods[key] == null ? noop : bind(methods[key], vm); * 四、处理data, * if (opts.data) { * initData(vm); * } else { * observe(vm._data = {}, true /* asRootData */); * } * 五、执行initData: * (1)先判断data的属性是否有与methods和props值同名 * (2)获取vm.data(若是为function,执行getData(data, vm)),代理proxy(vm, "_data", key); * (3)执行 observe(data, true /* asRootData */);递归观察 * 六、完成observe,具体看解释 */ initState(vm) initProvide(vm) // resolve provide after data/props callHook(vm, 'created') /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { vm._name = formatComponentName(vm, false) mark(endTag) measure(`vue ${vm._name} init`, startTag, endTag) } if (vm.$options.el) { vm.$mount(vm.$options.el) } } }
function observe (value, asRootData) { // 若是value不是是Object 或者是VNode这不用转换 if (!isObject(value) || value instanceof VNode) { return } var ob; // 若是已经转换就复用 if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( //一堆必要的条件判断 observerState.shouldConvert && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { //这才是observe主体 ob = new Observer(value); } if (asRootData && ob) { ob.vmCount++; } return ob }
var Observer = function Observer (value) { // 当asRootData = true时,其实能够将value当作vm.$options.data,后面都这样方便理解 this.value = value; /** * 为vm.data建立一个dep实例,能够理解为一个专属事件列表维护对象 * 例如: this.dep = { id : 156, subs : [] } * 实例方法: this.dep.__proto__ = { addSub, removeSub, depend, notify, constructor } */ this.dep = new Dep(); //记录关联的vm实例的数量 this.vmCount = 0; //为vm.data 添加__ob__属性,值为当前observe实例,而且转化为响应式数据。因此看一个value是否为响应式就能够看他有没有__ob__属性 def(value, '__ob__', this); //响应式数据转换分为数组、对象两种。 if (Array.isArray(value)) { var augment = hasProto ? protoAugment : copyAugment; augment(value, arrayMethods, arrayKeys); this.observeArray(value); } else { //对象的转换,并且walk是Observer的实例方法,请记住 this.walk(value); } };
该方法要将vm.data的全部属性都转化为getter/setter模式,因此vm.data只能是Object。数组的转换不同,这里暂不作讲解。数组
Observer.prototype.walk = function walk (obj) { // 获得key的列表 var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { //核心方法:定义响应式数据的方法 defineReactive(对象, 属性, 值);这样看是否是就很爽了 defineReactive(obj, keys[i], obj[keys[i]]); } };
function defineReactive ( obj, key, val, customSetter, //自定义setter,为了测试 shallow //是否只转换这一个属性后代无论控制参数,false :是,true : 否 ) { /** * 又是一个dep实例,其实做用与observe中的dep功能同样,不一样点: * 1.observe实例的dep对象是父级vm.data的订阅者维护对象 * 2.这个dep是vm.data的属性key的订阅者维护对象,由于val有可能也是对象 * 3.这里的dep没有写this.dep是由于defineReactive是一个方法,不是构造函数,因此使用闭包锁在内存中 */ var dep = new Dep(); // 获取key的属性描述符 var property = Object.getOwnPropertyDescriptor(obj, key); // 若是key属性不可设置,则退出该函数 if (property && property.configurable === false) { return } // 为了配合那些已经的定义了getter/setter的状况 var getter = property && property.get; var setter = property && property.set; //递归,由于没有传asRootData为true,因此vm.data的vmCount是部分计数的。由于它仍是属于vm的数据 var childOb = !shallow && observe(val); /** * 所有完成后observe也就完成了。可是,每一个属性的dep都没启做用。 * 这就是所谓的依赖收集了,后面继续。 */ Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); if (Array.isArray(value)) { dependArray(value); } } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (process.env.NODE_ENV !== 'production' && customSetter) { customSetter(); } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = !shallow && observe(newVal); dep.notify(); } }); }
一些我的理解: 一、Watcher 订阅者 能够将它理解为,要作什么。具体的体现就是Watcher的第二个参数expOrFn。 二、Observer 观察者 其实观察的体现就是getter/setter可以观察数据的变化(数组的实现不一样)。 三、dependency collection 依赖收集 订阅者(Watcher)是干事情的,是一些指令、方法、表达式的执行形式。它运行的过程当中确定离不开数据,因此就成了这些数据的依赖项目。由于离不开^_^数据。 数据是确定会变的,那么数据变了就得通知数据的依赖项目(Watcher)让他们再执行一下。 依赖同一个数据的依赖项目(Watcher)可能会不少,为了保证可以都通知到,因此须要收集一下。 四、Dep 依赖收集器构造函数 由于数据是由深度的,在不一样的深度有不一样的依赖,因此咱们须要一个容器来装起来。 Dep.target的做用是保证数据在收集依赖项(Watcher)时,watcher是对这个数据依赖的,而后一个个去收集的。
Watcher (vm, expOrFn, cb, options) 参数: {string | Function} expOrFn {Function | Object} callback {Object} [options] {boolean} deep {boolean} user {boolean} lazy {boolean} sync 在Vue的整个生命周期当中,会有4类地方会实例化Watcher: Vue实例化的过程当中有watch选项 Vue实例化的过程当中有computed计算属性选项 Vue原型上有挂载$watch方法: Vue.prototype.$watch,能够直接经过实例调用this.$watch方法 Vue生成了render函数,更新视图时 Watcher接收的参数当中expOrFn定义了用以获取watcher的getter函数。expOrFn能够有2种类型:string或function.若为string类型, 首先会经过parsePath方法去对string进行分割(仅支持.号形式的对象访问)。在除了computed选项外,其余几种实例化watcher的方式都 是在实例化过程当中完成求值及依赖的收集工做:this.value = this.lazy ? undefined : this.get().在Watcher的get方法中:
var Watcher = function Watcher ( vm, expOrFn, cb, options ) { this.vm = vm; vm._watchers.push(this); // options if (options) { this.deep = !!options.deep; this.user = !!options.user; this.lazy = !!options.lazy; this.sync = !!options.sync; } else { this.deep = this.user = this.lazy = this.sync = false; } //相关属性 this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers // this.deps = []; this.newDeps = []; //set类型的ids this.depIds = new _Set(); this.newDepIds = new _Set(); // 表达式 this.expression = process.env.NODE_ENV !== 'production' ? expOrFn.toString() : ''; // 建立一个getter if (typeof expOrFn === 'function') { this.getter = expOrFn; } else { this.getter = parsePath(expOrFn); if (!this.getter) { this.getter = function () {}; process.env.NODE_ENV !== 'production' && warn( "Failed watching path: \"" + expOrFn + "\" " + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.', vm ); } } this.value = this.lazy ? undefined : this.get();//执行get收集依赖项 };
经过设置观察值(this.value)调用this.get方法,执行this.getter.call(vm, vm),这个过程当中只要获取了某个响应式数据。那么确定会触发该数据的getter方法。由于当前的Dep.target = watcher。因此就将该watcher做为了这个响应数据的依赖项。由于watcher在执行过程当中的确须要、使用了它、因此依赖它。
Watcher.prototype.get = function get () { //将这个watcher观察者实例添加到Dep.target,代表当前为this.expressoin的依赖收集时间 pushTarget(this); var value; var vm = this.vm; try { /** * 执行this.getter.call(vm, vm): * 一、若是是function则至关于vm.expOrFn(vm),只要在这个方法执行的过程当中有从vm上获取属性值的都会触发该属性值的get方法从而完成依赖收集。由于如今Dep.target=this. * 二、若是是字符串(如a.b),那么this.getter.call(vm, vm)就至关于vm.a.b */ value = this.getter.call(vm, vm); } catch (e) { if (this.user) { handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\"")); } else { throw e } } finally { // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } popTarget(); this.cleanupDeps(); } return value };
Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { //依赖收集,这里又饶了一圈,看后面的解释 dep.depend(); if (childOb) { childOb.dep.depend(); if (Array.isArray(value)) { dependArray(value); } } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (process.env.NODE_ENV !== 'production' && customSetter) { customSetter(); } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = !shallow && observe(newVal); //数据变更出发全部依赖项 dep.notify(); } });
- 依赖收集具体动做:
//调用的本身dep的实例方法 Dep.prototype.depend = function depend () { if (Dep.target) { //调用的是当前Watcher实例的addDe方法,而且把dep对象传过去了 Dep.target.addDep(this); } }; Watcher.prototype.addDep = function addDep (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { //为这个watcher统计内部依赖了多少个数据,以及其余公用该数据的watcher this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { //继续为数据收集依赖项目的步骤 dep.addSub(this); } } }; Dep.prototype.addSub = function addSub (sub) { this.subs.push(sub); };
- 数据变更出发依赖动做:
Dep.prototype.notify = function notify () { // stabilize the subscriber list first var subs = this.subs.slice(); for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; //对当前watcher的处理 Watcher.prototype.update = function update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { this.run(); } else { queueWatcher(this); } }; //把一个观察者推入观察者队列。 //具备重复id的做业将被跳过,除非它是 //当队列被刷新时被推。 export function queueWatcher (watcher: Watcher) { const id = watcher.id if (has[id] == null) { has[id] = true if (!flushing) { queue.push(watcher) } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. let i = queue.length - 1 while (i > index && queue[i].id > watcher.id) { i-- } queue.splice(i + 1, 0, watcher) } // queue the flush if (!waiting) { waiting = true nextTick(flushSchedulerQueue) } } }