vue源码解读
2019-12-22 22:59:08 0 举报
AI智能生成
vue源码笔记
作者其他创作
大纲/内容
入口
vue\package.json
scripts: { dev: ... scripts/config.js ... :web-full-dev }
vue\scripts\config.js
web-full-dev: {
entry: resolve('web/entry-runtime-with-compiler.js')
}
entry: resolve('web/entry-runtime-with-compiler.js')
}
/* 扩展$mount */
vue\src\platforms\web\entry-runtime-with-compiler.js
vue\src\platforms\web\entry-runtime-with-compiler.js
const mount = Vue.prototype.$mount // 缓存$mount
// 对$mount进行覆盖及扩充,把传入的模板生成渲染函数
Vue.prototype.$mount = function ( ... ) {
el = el && query(el); // 获取传入的元素
const options = this.$options; // 获取实例的选项
if (!options.render) { // 如果选项中没有render
let template = options.template // 获取选项的template
if (template) {
// 如果有template的相关操作
}else if (el) {
template = getOuterHTML(el) // 如果有el就获取outerHtml
}
if (template) {
// 通过编译器得到render函数
const { render, staticRenderFns } = compileToFunctions(template, { ... }, this)
}
}
return mount.call(this, el, hydrating) // 把mount挂载到当前实例上
}
Vue.prototype.$mount = function ( ... ) {
el = el && query(el); // 获取传入的元素
const options = this.$options; // 获取实例的选项
if (!options.render) { // 如果选项中没有render
let template = options.template // 获取选项的template
if (template) {
// 如果有template的相关操作
}else if (el) {
template = getOuterHTML(el) // 如果有el就获取outerHtml
}
if (template) {
// 通过编译器得到render函数
const { render, staticRenderFns } = compileToFunctions(template, { ... }, this)
}
}
return mount.call(this, el, hydrating) // 把mount挂载到当前实例上
}
/* 实现$mount */
vue\src\platforms\web\runtime\index.js
vue\src\platforms\web\runtime\index.js
// 指令和组件的全局注册
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)
// 打补丁
Vue.prototype.__patch__ = inBrowser ? patch : noop
Vue.prototype.__patch__ = inBrowser ? patch : noop
// 把得到的组件挂载到当前实例
Vue.prototype.$mount = function ( ... ): Component {
return mountComponent(this, el, hydrating)
}
Vue.prototype.$mount = function ( ... ): Component {
return mountComponent(this, el, hydrating)
}
/* initGlobalAPI */
vue\src\core\index.js
vue\src\core\index.js
// 初始化全局API
initGlobalAPI(Vue)
initGlobalAPI(Vue)
路径:vue\src\core\global-api\index.js
// 全局工具函数的初始化
Vue.util = {
warn,
extend,
mergeOptions,
defineReactive
}
Vue.util = {
warn,
extend,
mergeOptions,
defineReactive
}
// 全局方法的初始化
Vue.set = set
Vue.delete = del
Vue.nextTick = nextTick
Vue.set = set
Vue.delete = del
Vue.nextTick = nextTick
Vue.observable = <T>(obj: T): T => {
observe(obj)
return obj
}
observe(obj)
return obj
}
initUse(Vue)
initMixin(Vue)
initExtend(Vue)
initAssetRegisters(Vue)
initMixin(Vue)
initExtend(Vue)
initAssetRegisters(Vue)
vue\src\core\instance\index.js
// Vue的全局构造函数
function Vue (options) {
this._init(options)
}
function Vue (options) {
this._init(options)
}
// 实现_init函数
initMixin(Vue)
initMixin(Vue)
路径:vue\src\core\instance\init.js
Vue.prototype._init = function ( ... ) {
if (options && options._isComponent) {
initInternalComponent(vm, options)
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm) // 整合自己的option和默认的option
}
}
if (options && options._isComponent) {
initInternalComponent(vm, options)
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm) // 整合自己的option和默认的option
}
}
// 初始化
initLifecycle(vm)
initEvents(vm)
initRender(vm)
callHook(vm, 'beforeCreate')
initInjections(vm) // resolve injections before data/props
initState(vm)
initProvide(vm) // resolve provide after data/props
callHook(vm, 'created')
initLifecycle(vm)
initEvents(vm)
initRender(vm)
callHook(vm, 'beforeCreate')
initInjections(vm) // resolve injections before data/props
initState(vm)
initProvide(vm) // resolve provide after data/props
callHook(vm, 'created')
路径:vue\src\core\instance\lifecycle.js
// initLifecycle初始化实例组件的常用属性
vm.$parent = parent
vm.$root = parent ? parent.$root : vm
vm.$children = []
vm.$refs = {}
vm._watcher = null
vm.$parent = parent
vm.$root = parent ? parent.$root : vm
vm.$children = []
vm.$refs = {}
vm._watcher = null
路径:vue\src\core\instance\events.js
// initEvents事件的初始化
const listeners = vm.$options._parentListeners
if (listeners) {
// 如果父级有监听器,就更新组件的监听器
updateComponentListeners(vm, listeners)
}
const listeners = vm.$options._parentListeners
if (listeners) {
// 如果父级有监听器,就更新组件的监听器
updateComponentListeners(vm, listeners)
}
路径:vue\src\core\instance\render.js
// $slots和$scopedSlots初始化。createElement的声明。$attrs和$listeners的响应化
const options = vm.$options
const parentVnode = vm.$vnode = options._parentVnode // the placeholder node in parent tree
const renderContext = parentVnode && parentVnode.context
vm.$slots = resolveSlots(options._renderChildren, renderContext)
vm.$scopedSlots = emptyObject
// 把createElement函数挂载到当前组件上,编译器编译的时候需要用。柯里化
vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
// 用户编写渲染函数使用这个
vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)
const parentData = parentVnode && parentVnode.data
// 两个响应式
defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, null, true)
defineReactive(vm, '$listeners', options._parentListeners || emptyObject, null, true)
const options = vm.$options
const parentVnode = vm.$vnode = options._parentVnode // the placeholder node in parent tree
const renderContext = parentVnode && parentVnode.context
vm.$slots = resolveSlots(options._renderChildren, renderContext)
vm.$scopedSlots = emptyObject
// 把createElement函数挂载到当前组件上,编译器编译的时候需要用。柯里化
vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
// 用户编写渲染函数使用这个
vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)
const parentData = parentVnode && parentVnode.data
// 两个响应式
defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, null, true)
defineReactive(vm, '$listeners', options._parentListeners || emptyObject, null, true)
路径:vue\src\core\instance\state.js
// 执行各种数据状态初始化,包括数据响应化
vm._watchers = []
const opts = vm.$options
// 初始化所有属性
if (opts.props) initProps(vm, opts.props)
// 初始化所有回调函数
if (opts.methods) initMethods(vm, opts.methods)
// 数据响应化
if (opts.data) {
initData(vm)
} else {
observe(vm._data = {}, true /* asRootData */)
}
// 初始化computed
if (opts.computed) initComputed(vm, opts.computed)
// 初始化watch监听
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
vm._watchers = []
const opts = vm.$options
// 初始化所有属性
if (opts.props) initProps(vm, opts.props)
// 初始化所有回调函数
if (opts.methods) initMethods(vm, opts.methods)
// 数据响应化
if (opts.data) {
initData(vm)
} else {
observe(vm._data = {}, true /* asRootData */)
}
// 初始化computed
if (opts.computed) initComputed(vm, opts.computed)
// 初始化watch监听
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
function initData (vm: Component) {
let data = vm.$options.data
// 如果选项中的data是函数就调用getData得到正确的格式,否则就直接取用或定义为空对象
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
// proxy data on instance 把data代理到当前实例
const keys = Object.keys(data)
const props = vm.$options.props
const methods = vm.$options.methods
// observe data 劫持监听data做数据响应式
observe(data, true /* asRootData */)
}
let data = vm.$options.data
// 如果选项中的data是函数就调用getData得到正确的格式,否则就直接取用或定义为空对象
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
// proxy data on instance 把data代理到当前实例
const keys = Object.keys(data)
const props = vm.$options.props
const methods = vm.$options.methods
// observe data 劫持监听data做数据响应式
observe(data, true /* asRootData */)
}
路径:vue-dev\src\core\observer\index.js
// observe方法返回一个Observer实例
let ob: Observer | void
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__ // 如果data中有observe就用本来有的
} else if (
shouldObserve &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value) // 如果没有就new一个Observer观察者实例
}
return ob // 返回观察者
let ob: Observer | void
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__ // 如果data中有observe就用本来有的
} else if (
shouldObserve &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value) // 如果没有就new一个Observer观察者实例
}
return ob // 返回观察者
// Observer类根据数据类型做数据响应化
export class Observer {
value: any;
dep: Dep;
vmCount: number; // number of vms that have this object as root $data
constructor (value: any) {
this.value = value
this.dep = new Dep()
this.vmCount = 0
def(value, '__ob__', this)
// 覆盖数组原型
if (Array.isArray(value)) {
if (hasProto) {
// 替换数组原型 value.__proto__ = arraryMethods
protoAugment(value, arrayMethods)
} else {
copyAugment(value, arrayMethods, arrayKeys)
}
this.observeArray(value)
} else {
this.walk(value)
}
}
// 如果data是对象的处理方法
walk (obj: Object) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i])
}
}
// 如果data是数组的处理方法
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
}
export class Observer {
value: any;
dep: Dep;
vmCount: number; // number of vms that have this object as root $data
constructor (value: any) {
this.value = value
this.dep = new Dep()
this.vmCount = 0
def(value, '__ob__', this)
// 覆盖数组原型
if (Array.isArray(value)) {
if (hasProto) {
// 替换数组原型 value.__proto__ = arraryMethods
protoAugment(value, arrayMethods)
} else {
copyAugment(value, arrayMethods, arrayKeys)
}
this.observeArray(value)
} else {
this.walk(value)
}
}
// 如果data是对象的处理方法
walk (obj: Object) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i])
}
}
// 如果data是数组的处理方法
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
}
路径:vue-dev\src\core\observer\array.js
// 数组响应化。数组数据变化的侦测跟对象不同,通常操作数组使用push、splice、pop等方法,此时没法知道数据的变化。
// Vue采取的办法是拦截这些方法并通知dep
// 数组原型
const arrayProto = Array.prototype
// 修改后的原型
export const arrayMethods = Object.create(arrayProto)
// 七个待修改的数组方法
const methodsToPatch = [
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
/**
* 拦截这些方法并发出通知
*/
methodsToPatch.forEach(function (method) {
// 原始数组方法
const original = arrayProto[method]
// 修改这些方法的descriptor。def相当是defineProperty
def(arrayMethods, method, function mutator (...args) {
// 原始操作
const result = original.apply(this, args)
// 获取ob实例用于发送通知
const ob = this.__ob__
// 三个能新增元素的方法特殊处理
let inserted
switch (method) {
case 'push':
case 'unshift':
inserted = args
break
case 'splice':
inserted = args.slice(2)
break
}
// 若有新增则做响应处理
if (inserted) ob.observeArray(inserted)
// 通知更新
ob.dep.notify()
return result
})
})
// Vue采取的办法是拦截这些方法并通知dep
// 数组原型
const arrayProto = Array.prototype
// 修改后的原型
export const arrayMethods = Object.create(arrayProto)
// 七个待修改的数组方法
const methodsToPatch = [
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
/**
* 拦截这些方法并发出通知
*/
methodsToPatch.forEach(function (method) {
// 原始数组方法
const original = arrayProto[method]
// 修改这些方法的descriptor。def相当是defineProperty
def(arrayMethods, method, function mutator (...args) {
// 原始操作
const result = original.apply(this, args)
// 获取ob实例用于发送通知
const ob = this.__ob__
// 三个能新增元素的方法特殊处理
let inserted
switch (method) {
case 'push':
case 'unshift':
inserted = args
break
case 'splice':
inserted = args.slice(2)
break
}
// 若有新增则做响应处理
if (inserted) ob.observeArray(inserted)
// 通知更新
ob.dep.notify()
return result
})
})
// defineReactive方法定义对象属性的getter/setter方法,getter添加依赖,setter通知更新
const dep = new Dep()
const property = Object.getOwnPropertyDescriptor(obj, key)
if (property && property.configurable === false) {
return
}
const getter = property && property.get
const setter = property && property.set
if ((!getter || setter) && arguments.length === 2) {
val = obj[key] // 一个key对应一个Dep实例
}
// 递归执行子对象响应化
let childOb = !shallow && observe(val)
// 定义对象属性的getter/setter
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend() // getter被调用的时如果存在依赖就追加
if (childOb) {
childOb.dep.depend() // 若也存在子Observer,则依赖也追加到子ob
if (Array.isArray(value)) {
dependArray(value) // 数组的处理方式
}
}
}
return value
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter()
}
if (getter && !setter) return
// 如果值变了就更新值
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal) // 递归更新子对象
dep.notify() // 通知更新
}
})
// 数组的所有项添加依赖,数据变化的时候就可以通过__ob__.dep发送通知
function dependArray (value: Array<any>) {
for (let e, i = 0, l = value.length; i < l; i++) {
e = value[i]
e && e.__ob__ && e.__ob__.dep.depend()
if (Array.isArray(e)) {
dependArray(e)
}
}
}
const dep = new Dep()
const property = Object.getOwnPropertyDescriptor(obj, key)
if (property && property.configurable === false) {
return
}
const getter = property && property.get
const setter = property && property.set
if ((!getter || setter) && arguments.length === 2) {
val = obj[key] // 一个key对应一个Dep实例
}
// 递归执行子对象响应化
let childOb = !shallow && observe(val)
// 定义对象属性的getter/setter
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend() // getter被调用的时如果存在依赖就追加
if (childOb) {
childOb.dep.depend() // 若也存在子Observer,则依赖也追加到子ob
if (Array.isArray(value)) {
dependArray(value) // 数组的处理方式
}
}
}
return value
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter()
}
if (getter && !setter) return
// 如果值变了就更新值
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal) // 递归更新子对象
dep.notify() // 通知更新
}
})
// 数组的所有项添加依赖,数据变化的时候就可以通过__ob__.dep发送通知
function dependArray (value: Array<any>) {
for (let e, i = 0, l = value.length; i < l; i++) {
e = value[i]
e && e.__ob__ && e.__ob__.dep.depend()
if (Array.isArray(e)) {
dependArray(e)
}
}
}
路径:vue-dev\src\core\observer\dep.js
// Dep类负责管理一组Watcher,包括watcher的增删以及通知更新
static target: ?Watcher; // 依赖收集时的Watcher引用
id: number;
subs: Array<Watcher>; // Watcher数组
constructor () {
this.id = uid++
this.subs = []
}
// 添加Watcher实例
addSub (sub: Watcher) {
this.subs.push(sub)
}
// 移除Watcher实例
removeSub (sub: Watcher) {
remove(this.subs, sub)
}
// 添加Watcher和Dep的相互引用
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
// 批量通知更新
notify () {
const subs = this.subs.slice()
if (process.env.NODE_ENV !== 'production' && !config.async) {
subs.sort((a, b) => a.id - b.id)
}
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
static target: ?Watcher; // 依赖收集时的Watcher引用
id: number;
subs: Array<Watcher>; // Watcher数组
constructor () {
this.id = uid++
this.subs = []
}
// 添加Watcher实例
addSub (sub: Watcher) {
this.subs.push(sub)
}
// 移除Watcher实例
removeSub (sub: Watcher) {
remove(this.subs, sub)
}
// 添加Watcher和Dep的相互引用
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
// 批量通知更新
notify () {
const subs = this.subs.slice()
if (process.env.NODE_ENV !== 'production' && !config.async) {
subs.sort((a, b) => a.id - b.id)
}
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
路径:vue-dev\src\core\observer\watcher.js
// Watcher类 解析一个表达式并收集依赖,当数值发生变化触发回到函数,常用于watcher API和指令中
// 每个组件都有一个对应的Watcher,当数值发生改变调用其update函数并重新渲染
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
this.vm = vm
// 组件保存render watcher
if (isRenderWatcher) {
vm._watcher = this
}
// 组件保存非render watcher
vm._watchers.push(this)
// options
// 将表达式解析为getter函数
if (typeof expOrFn === 'function') {
// 那些和组件实例对应的watcher一起创建时会传递组件更新函数updateComponent
this.getter = expOrFn // 如果是函数直接指定为getter
} else {
// 这种是$watch传递进来的表达式,它们需要被解析成函数
this.getter = parsePath(expOrFn)
if (!this.getter) {
this.getter = noop
}
}
this.value = this.lazy ? undefined : this.get() // 如果是非延迟watcher则立即执行getter
}
// 模拟getter,重新收集依赖
get () {
pushTarget(this)
let value
const vm = this.vm
try {
// 从组件中获取value并触发依赖收集
value = this.getter.call(vm, vm)
} catch (e) {
} finally {
// 递归触发深层属性
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps()
}
return value
}
addDep (dep: Dep) {
const id = dep.id
if (!this.newDepIds.has(id)) {
// watcher添加dep引用
this.newDepIds.add(id)
this.newDeps.push(dep)
if (!this.depIds.has(id)) {
// dep添加watcher引用
dep.addSub(this)
}
}
}
update () {
// 更新逻辑
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
// 默认lazy和sync都是false
queueWatcher(this)
}
}
// 每个组件都有一个对应的Watcher,当数值发生改变调用其update函数并重新渲染
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
this.vm = vm
// 组件保存render watcher
if (isRenderWatcher) {
vm._watcher = this
}
// 组件保存非render watcher
vm._watchers.push(this)
// options
// 将表达式解析为getter函数
if (typeof expOrFn === 'function') {
// 那些和组件实例对应的watcher一起创建时会传递组件更新函数updateComponent
this.getter = expOrFn // 如果是函数直接指定为getter
} else {
// 这种是$watch传递进来的表达式,它们需要被解析成函数
this.getter = parsePath(expOrFn)
if (!this.getter) {
this.getter = noop
}
}
this.value = this.lazy ? undefined : this.get() // 如果是非延迟watcher则立即执行getter
}
// 模拟getter,重新收集依赖
get () {
pushTarget(this)
let value
const vm = this.vm
try {
// 从组件中获取value并触发依赖收集
value = this.getter.call(vm, vm)
} catch (e) {
} finally {
// 递归触发深层属性
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps()
}
return value
}
addDep (dep: Dep) {
const id = dep.id
if (!this.newDepIds.has(id)) {
// watcher添加dep引用
this.newDepIds.add(id)
this.newDeps.push(dep)
if (!this.depIds.has(id)) {
// dep添加watcher引用
dep.addSub(this)
}
}
}
update () {
// 更新逻辑
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
// 默认lazy和sync都是false
queueWatcher(this)
}
}
路径:vue-dev\src\core\observer\scheduler.js
// 异步更新队列
// 执行watcher入队操作,如果id重复就跳过
export function queueWatcher (watcher: Watcher) {
const id = watcher.id
if (has[id] == null) { // id不存在才入队
has[id] = true
if (!flushing) { // 如果没有在执行更新,则插入到队尾
queue.push(watcher)
} else {
// 若已更新,根据id插入队列
// 若已经更新过了,就在下次刷新时立即执行
let i = queue.length - 1
while (i > index && queue[i].id > watcher.id) {
i--
}
queue.splice(i + 1, 0, watcher)
}
// 刷新队列
if (!waiting) {
waiting = true
if (process.env.NODE_ENV !== 'production' && !config.async) {
flushSchedulerQueue()
return
}
nextTick(flushSchedulerQueue)
}
}
}
// 执行watcher入队操作,如果id重复就跳过
export function queueWatcher (watcher: Watcher) {
const id = watcher.id
if (has[id] == null) { // id不存在才入队
has[id] = true
if (!flushing) { // 如果没有在执行更新,则插入到队尾
queue.push(watcher)
} else {
// 若已更新,根据id插入队列
// 若已经更新过了,就在下次刷新时立即执行
let i = queue.length - 1
while (i > index && queue[i].id > watcher.id) {
i--
}
queue.splice(i + 1, 0, watcher)
}
// 刷新队列
if (!waiting) {
waiting = true
if (process.env.NODE_ENV !== 'production' && !config.async) {
flushSchedulerQueue()
return
}
nextTick(flushSchedulerQueue)
}
}
}
路径:vue-dev\src\core\util\next-tick.js
// nextTick按照特定的异步策略执行队列刷新操作
export function nextTick (cb?: Function, ctx?: Object) {
let _resolve
// cb不是立即执行,是加入到数组中,等待调用
callbacks.push(() => {
if (cb) {
try {
cb.call(ctx) // 真正执行cb
} catch (e) {
handleError(e, ctx, 'nextTick')
}
} else if (_resolve) {
_resolve(ctx)
}
})
// 没有处在挂起状态就执行异步队列
if (!pending) {
pending = true
timerFunc() // 时间函数
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
// 定义时间函数
let timerFunc
// nextTick异步行为通过微任务队列
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
timerFunc = () => {
p.then(flushCallbacks)
if (isIOS) setTimeout(noop)
}
isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// 不能用Promise时
let counter = 1
const observer = new MutationObserver(flushCallbacks)
const textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = () => {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
// 退化到setImmediate,利用的是宏任务队列
timerFunc = () => {
setImmediate(flushCallbacks)
}
} else {
// 最后退化到setTimeout,也是宏任务队列
timerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
export function nextTick (cb?: Function, ctx?: Object) {
let _resolve
// cb不是立即执行,是加入到数组中,等待调用
callbacks.push(() => {
if (cb) {
try {
cb.call(ctx) // 真正执行cb
} catch (e) {
handleError(e, ctx, 'nextTick')
}
} else if (_resolve) {
_resolve(ctx)
}
})
// 没有处在挂起状态就执行异步队列
if (!pending) {
pending = true
timerFunc() // 时间函数
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
// 定义时间函数
let timerFunc
// nextTick异步行为通过微任务队列
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
timerFunc = () => {
p.then(flushCallbacks)
if (isIOS) setTimeout(noop)
}
isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// 不能用Promise时
let counter = 1
const observer = new MutationObserver(flushCallbacks)
const textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = () => {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
// 退化到setImmediate,利用的是宏任务队列
timerFunc = () => {
setImmediate(flushCallbacks)
}
} else {
// 最后退化到setTimeout,也是宏任务队列
timerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
defineReactive中的getter和setter对应着订阅和发布行为
Dep相当于主题Subject,维护订阅者、通知观察者更新
Watcher相当于观察者Observer,执行更新
Vue中的Observer不是上面说的观察者,它和data中的对象一一对应,有内嵌的对象就会有child Obsever与之对应
Dep相当于主题Subject,维护订阅者、通知观察者更新
Watcher相当于观察者Observer,执行更新
Vue中的Observer不是上面说的观察者,它和data中的对象一一对应,有内嵌的对象就会有child Obsever与之对应
stateMixin(Vue)
路径:vue\src\core\instance\state.js
// 定义$data、$props两个实例属性和$set、$delete、$watch三个实例方法
const dataDef = {}
dataDef.get = function () { return this._data }
const propsDef = {}
propsDef.get = function () { return this._props }
Object.defineProperty(Vue.prototype, '$data', dataDef)
Object.defineProperty(Vue.prototype, '$props', propsDef)
Vue.prototype.$set = set
Vue.prototype.$delete = del
// $watch是与数据响应机制息息相关的API,它指定一个监控表达式,当数据变化时执行回调函数
Vue.prototype.$watch = function (
expOrFn: string | Function,
cb: any,
options?: Object
): Function {
const vm: Component = this
// 对象形式回调解析
if (isPlainObject(cb)) {
return createWatcher(vm, expOrFn, cb, options)
}
options = options || {}
options.user = true
// 创建watcher监听数值变化
const watcher = new Watcher(vm, expOrFn, cb, options)
if (options.immediate) { // 如果实例的选项中有immediate就立即执行一次cb }
return function unwatchFn () {
watcher.teardown() // 返回一个监听的销毁
}
}
const dataDef = {}
dataDef.get = function () { return this._data }
const propsDef = {}
propsDef.get = function () { return this._props }
Object.defineProperty(Vue.prototype, '$data', dataDef)
Object.defineProperty(Vue.prototype, '$props', propsDef)
Vue.prototype.$set = set
Vue.prototype.$delete = del
// $watch是与数据响应机制息息相关的API,它指定一个监控表达式,当数据变化时执行回调函数
Vue.prototype.$watch = function (
expOrFn: string | Function,
cb: any,
options?: Object
): Function {
const vm: Component = this
// 对象形式回调解析
if (isPlainObject(cb)) {
return createWatcher(vm, expOrFn, cb, options)
}
options = options || {}
options.user = true
// 创建watcher监听数值变化
const watcher = new Watcher(vm, expOrFn, cb, options)
if (options.immediate) { // 如果实例的选项中有immediate就立即执行一次cb }
return function unwatchFn () {
watcher.teardown() // 返回一个监听的销毁
}
}
eventsMixin(Vue)
路径:vue-dev\src\core\instance\events.js
// 定义$on、$once、$off、$emit四个事件相关的实例方法
Vue.prototype.$on = function (event: string | Array<string>, fn: Function): Component { ... }
Vue.prototype.$once = function (event: string, fn: Function): Component { ... }
Vue.prototype.$off = function (event?: string | Array<string>, fn?: Function): Component { ... }
Vue.prototype.$emit = function (event: string): Component { ... }
Vue.prototype.$on = function (event: string | Array<string>, fn: Function): Component { ... }
Vue.prototype.$once = function (event: string, fn: Function): Component { ... }
Vue.prototype.$off = function (event?: string | Array<string>, fn?: Function): Component { ... }
Vue.prototype.$emit = function (event: string): Component { ... }
lifecycleMixin(Vue)
路径:vue-dev\src\core\instance\lifecycle.js
// 定义_update、$forceUpdate、$destroy三个生命周期钩子函数
// _update方法是组件周期中关键方法,组件触发更新就会调用该函数,执行组件的diff和patch等方法
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
const vm: Component = this
const prevEl = vm.$el
const prevVnode = vm._vnode
const restoreActiveInstance = setActiveInstance(vm)
vm._vnode = vnode
if (!prevVnode) {
// initial render 第一次初始化时调用
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
} else {
// updates 更新时调用
vm.$el = vm.__patch__(prevVnode, vnode)
}
}
Vue.prototype.$forceUpdate = function () { ... }
Vue.prototype.$destroy = function () { ... }
// _update方法是组件周期中关键方法,组件触发更新就会调用该函数,执行组件的diff和patch等方法
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
const vm: Component = this
const prevEl = vm.$el
const prevVnode = vm._vnode
const restoreActiveInstance = setActiveInstance(vm)
vm._vnode = vnode
if (!prevVnode) {
// initial render 第一次初始化时调用
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
} else {
// updates 更新时调用
vm.$el = vm.__patch__(prevVnode, vnode)
}
}
Vue.prototype.$forceUpdate = function () { ... }
Vue.prototype.$destroy = function () { ... }
renderMixin(Vue)
路径:vue-dev\src\core\instance\render.js
// 定义$nextTick和_render函数
Vue.prototype.$nextTick = function (fn: Function) {
return nextTick(fn, this)
}
Vue.prototype._render = function (): VNode {
const vm: Component = this
const { render, _parentVnode } = vm.$options
if (_parentVnode) {
vm.$scopedSlots = normalizeScopedSlots(
_parentVnode.data.scopedSlots,
vm.$slots,
vm.$scopedSlots
)
}
vm.$vnode = _parentVnode
// render self
let vnode
try {
currentRenderingInstance = vm
vnode = render.call(vm._renderProxy, vm.$createElement)
} ......
vnode.parent = _parentVnode
return vnode
}
Vue.prototype.$nextTick = function (fn: Function) {
return nextTick(fn, this)
}
Vue.prototype._render = function (): VNode {
const vm: Component = this
const { render, _parentVnode } = vm.$options
if (_parentVnode) {
vm.$scopedSlots = normalizeScopedSlots(
_parentVnode.data.scopedSlots,
vm.$slots,
vm.$scopedSlots
)
}
vm.$vnode = _parentVnode
// render self
let vnode
try {
currentRenderingInstance = vm
vnode = render.call(vm._renderProxy, vm.$createElement)
} ......
vnode.parent = _parentVnode
return vnode
}
0 条评论
下一页