在vue源码中的src/core/global-api目录的index下,初始化了全局API,如下:
initGlobalAPI
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.
Vue.util = {
warn,
extend,
mergeOptions,
defineReactive
}
Vue.set = set
Vue.delete = del
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
extend(Vue.options.components, builtInComponents)
initUse(Vue)
initMixin(Vue)
initExtend(Vue)
initAssetRegisters(Vue)
}
可以看到,在initGlobalAPI中首先给Vue添加了一些config配置属性,这些配置如果修改则会报出警告,这对全局API的分析无影响。接下来在Vue.util的属性中添加了一些方法,可以通过Vue.util.[xx]的方式访问这些方法,但不推荐这么做,util中的方法可能会不定期变更,当然这对全局API的分析也无影响。
接下来给构造函数Vue初始化了一些静态API,set、delete、nextTick 这些方法
Vue.options = Object.create(null)
ASSET_TYPES.forEach(type => {
Vue.options[type + 's'] = Object.create(null)
})
Vue.options._base = Vue
export const ASSET_TYPES = [
'component',
'directive',
'filter'
]
这段代码是给Vue的options对象上初始化了一些对象,结果如下:
通过extend函数,给Vue.components上添加了keepAlive组件,这也是为什么我们能直接使用keepAlive组件的原因
export function extend (to: Object, _from: ?Object): Object {
for (const key in _from) {
to[key] = _from[key]
}
return to
}
接下来执行一些初始化方法,在构造函数Vue上添加了use、mixin、extend、components、directive、filter这些方法。接下来对挂载的全局方法进行详细分析。
1.set
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
export function set(target: Array<any> | Object, key: any, val: any): any {
if (process.env.NODE_ENV !== 'production' &&
(isUndef(target) || isPrimitive(target))
) {
warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`)
}
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key)
target.splice(key, 1, val)
return val
}
if (key in target && !(key in Object.prototype)) {
target[key] = val
return val
}
const ob = (target: any).__ob__
if (target._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
)
return val
}
if (!ob) {
target[key] = val
return val
}
defineReactive(ob.value, key, val)
ob.dep.notify()
return val
}
export function isUndef (v: any): boolean %checks {
return v === undefined || v === null
}
export function isPrimitive (value: any): boolean %checks {
return (
typeof value === 'string' ||
typeof value === 'number' ||
// $flow-disable-line
typeof value === 'symbol' ||
typeof value === 'boolean'
)
}
set方法只能对数组或者对象生效,如果设置的属性值为undefined, null, or primitive value则会发出警告,接下来对设置的属性做判断,如果在数组或者对象中已经存在,则赋予新值并返回;
接下来看下该对象是否含有属性__ob__(该对象是否监听过的标志),被监听的对象也不能是一个vue实例,否则报错;
如果该对象未被监听,则直接返回该值,
defineReactive(ob.value, key, val)
ob.dep.notify()
若一切正常,则给该对象添加响应式属性(通过defineReactive),并通知依赖(通过notify)做相应变更,这两个方法是响应式原理的重要方法,这里不做赘述,但从这里可以看出,Vue.set这个方法是给一个已存在的对象的动态新增属性设置成响应式。
(对于对象或者数组的动态新增方法,没有set的情况下,是不会响应式的,笔者曾经踩过这个坑,所以源码还是有必要学习的啊!!!)
2.delete
/**
* Delete a property and trigger change if necessary.
*/
export function del(target: Array<any> | Object, key: any) {
if (process.env.NODE_ENV !== 'production' &&
(isUndef(target) || isPrimitive(target))
) {
warn(`Cannot delete reactive property on undefined, null, or primitive value: ${(target: any)}`)
}
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.splice(key, 1)
return
}
const ob = (target: any).__ob__
if (target._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid deleting properties on a Vue instance or its root $data ' +
'- just set it to null.'
)
return
}
if (!hasOwn(target, key)) {
return
}
delete target[key]
if (!ob) {
return
}
ob.dep.notify()
}
delete方法与set方法很类似,前面的逻辑跟set是一样的,如果这个属性不在对象中包含,则直接返回,否则通过原生语法delete该属性,如果对象中有__ob__对象,则通知依赖做相应变更;
Vue.prototype.$set = set
Vue.prototype.$delete = del
源码中还有上面这段代码,使用原型的方式挂载了set和del方法,这就是我们为什么可以使用this.$xx去调用set和del。
3.nextTick
js的执行是单线程的,主线程的执行过程就是一个tick,而所有的异步结果都是通过 “任务队列” 来调度,这其中就涉及到了宏任务与微任务,在浏览器环境中,常见的 macro task 有 setTimeout、MessageChannel、postMessage、setImmediate;常见的 micro task 有 MutationObsever 和 Promise.then,这里不做赘述。
接下来看nextTick源码:
const callbacks = []
let pending = false
export function nextTick (cb?: Function, ctx?: Object) {
let _resolve
callbacks.push(() => {
if (cb) {
try {
cb.call(ctx)
} catch (e) {
handleError(e, ctx, 'nextTick')
}
} else if (_resolve) {
_resolve(ctx)
}
})
if (!pending) {
pending = true
if (useMacroTask) {
macroTimerFunc()
} else {
microTimerFunc()
}
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
首先抛弃_resolve的逻辑(这是为实现promise而准备的,下文会提到),
该函数首先会向callbacks数组中推入一个匿名函数,该匿名函数执行的时候会触发传入的callback,再判断pending,这个pending刚开始的时候是false,进入后赋值为true,也就确保这个逻辑只会执行一次,再判断useMacroTask,根据浏览器的支持,确定不同的执行方式。
// Here we have async deferring wrappers using both microtasks and (macro) tasks.
// In < 2.4 we used microtasks everywhere, but there are some scenarios where
// microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690) or even between bubbling of the same
// event (#6566). However, using (macro) tasks everywhere also has subtle problems
// when state is changed right before repaint (e.g. #6813, out-in transitions).
// Here we use microtask by default, but expose a way to force (macro) task when
// needed (e.g. in event handlers attached by v-on).
let microTimerFunc
let macroTimerFunc
let useMacroTask = false
// Determine (macro) task defer implementation.
// Technically setImmediate should be the ideal choice, but it's only available
// in IE. The only polyfill that consistently queues the callback after all DOM
// events triggered in the same loop is by using MessageChannel.
/* istanbul ignore if */
if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
macroTimerFunc = () => {
setImmediate(flushCallbacks)
}
} else if (typeof MessageChannel !== 'undefined' && (
isNative(MessageChannel) ||
// PhantomJS
MessageChannel.toString() === '[object MessageChannelConstructor]'
)) {
const channel = new MessageChannel()
const port = channel.port2
channel.port1.onmessage = flushCallbacks
macroTimerFunc = () => {
port.postMessage(1)
}
} else {
/* istanbul ignore next */
macroTimerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
// Determine microtask defer implementation.
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
microTimerFunc = () => {
p.then(flushCallbacks)
// in problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) setTimeout(noop)
}
} else {
// fallback to macro
microTimerFunc = macroTimerFunc
}
/**
* Wrap a function so that if any code inside triggers state change,
* the changes are queued using a (macro) task instead of a microtask.
*/
export function withMacroTask (fn: Function): Function {
return fn._withTask || (fn._withTask = function () {
useMacroTask = true
const res = fn.apply(null, arguments)
useMacroTask = false
return res
})
}
可以看到会优先检测浏览器是否支持原生 setImmediate,不支持的话再去检测是否支持原生的MessageChannel,如果也不支持的话就会降级为 setTimeout 0;而对于 micro task 的实现,则检测浏览器是否原生支持 Promise,不支持的话直接指向 macro task 的实现,而这些函数其实最终都是会执行flushCallbacks。
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
可以看到,flushCallbacks中将pending赋值为了false,再依次执行了下一个tick中的所有的callback。
此外,回到_resolve变量,除了传入回调的方式外,nextTick也支持promise.then,当没有cb传入的时候,会执行:
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
在下一个tick执行的时候则会走到else if逻辑,也就可以通过.then的方式去执行。
if (cb) {
try {
cb.call(ctx)
} catch (e) {
handleError(e, ctx, 'nextTick')
}
} else if (_resolve) {
_resolve(ctx)
}
由以上可知,nextick函数也就是将所有的回调函数收集放在下一个tick中去执行的。
$nextTick
Vue.prototype.$nextTick = function (fn: Function) {
return nextTick(fn, this)
}
在构造函数Vue的原型上也挂载了nextTick方法,这就是我们为什么也可以使用this.$nextTick去调用nextTick的原因。
4.use、mixin
Vue.use与mixin的源码大家可以去看我的另一篇源码分析从初始化vuex的角度分析use、mixin,里面通过对Vue.use(Store)过程的分析,对use、mixin的理解更形象具体。
对于use函数,其实核心就是执行了传入的插件的install方法:
export function initUse (Vue: GlobalAPI) {
Vue.use = function (plugin: Function | Object) {
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// additional parameters
const args = toArray(arguments, 1)
args.unshift(this)
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
plugin.apply(null, args)
}
installedPlugins.push(plugin)
return this
}
}
对于mixin函数,核心是执行了mergeOptions函数,也就是向Vue.options添加mixin对象
export function initMixin (Vue: GlobalAPI) {
Vue.mixin = function (mixin: Object) {
this.options = mergeOptions(this.options, mixin)
return this
}
}
其中,mergeOptions函数中对于不同的属性有不同的合并策略,比如钩子函数
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
export function mergeOptions (
parent: Object,
child: Object,
vm?: Component
): Object {
if (process.env.NODE_ENV !== 'production') {
checkComponents(child)
}
if (typeof child === 'function') {
child = child.options
}
normalizeProps(child, vm)
normalizeInject(child, vm)
normalizeDirectives(child)
const extendsFrom = child.extends
if (extendsFrom) {
parent = mergeOptions(parent, extendsFrom, vm)
}
if (child.mixins) {
for (let i = 0, l = child.mixins.length; i < l; i++) {
parent = mergeOptions(parent, child.mixins[i], vm)
}
}
const options = {}
let key
for (key in parent) {
mergeField(key)
}
for (key in child) {
if (!hasOwn(parent, key)) {
mergeField(key)
}
}
function mergeField (key) {
const strat = strats[key] || defaultStrat
options[key] = strat(parent[key], child[key], vm, key)
}
return options
}
LIFECYCLE_HOOKS.forEach(hook => {
strats[hook] = mergeHook
})
function mergeHook (
parentVal: ?Array<Function>,
childVal: ?Function | ?Array<Function>
): ?Array<Function> {
return childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal
}
对于钩子函数,会通过parentVal.concat(childVal)合并为一个数组混合到Vue.options对象上,执行顺序是从前到后。
if (child.mixins) {
for (let i = 0, l = child.mixins.length; i < l; i++) {
parent = mergeOptions(parent, child.mixins[i], vm)
}
}
对于传入的mixin对象有mixins属性的情况下,先将mixins属性中的钩子函数合并到parent后面,再合并mixin对象中的钩子函数,最终的执行顺序为:
Vue.options上面的钩子函数–>mixin对象上mixins属性对象上的钩子函数–>mixin对象上的钩子函数
5.extend
。。。未完待续