vue源码解析
Vue定义全局属性
// core/global-api/index.js
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.'
)
}
}
// 定义config全局属性
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
// 定义observable全局方法
Vue.observable = <T>(obj: T): T => {
observe(obj)
return obj
}
//定义options全局属性,options对象定义了components、directives、filter属性
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
// 把内置组件keep-alive的属性混合到Vue.options.components
extend(Vue.options.components, builtInComponents)
// 定义全局use、mixin、extend、
initUse(Vue)
initMixin(Vue)
initExtend(Vue)
initAssetRegisters(Vue)
}全局方法use
用于安装Vue插件
重要:Vue.options对象包括全局混入的属性和全局components, directives, filters属性
全局方法mixin
用于合并options(data, props, method 等)
全局方法extend
定义全局component, directive, filter方法
Vue实例化
Vue构造函数实例调用了_init方法
Vue构造函数
mergeOptions 函数
mergeOptions 函数合并options,在这里传入了 resolveConstructorOptions(vm.constructor) 与options 参数,options 是Vue实例化传入的参数。返回值赋给vm.$options
resolveConstructorOptions
resolveConstructorOptions拿到构造函数上包括所有父类的options属性
如果是组件,执行此函数
初始化Vue生命周期相关属性
初始化Vue父组件为当前组件注册的事件监听器
修饰符
前缀
.passive
&
.capture
!
.capture
!
.capture.once 或 .once.capture
~!
事件修饰符前缀
初始化事件监听器对象
通过v-on:clickHandler绑定的事件监听器对象会编译成如下结构。
add remove方法
add remove方法把$attrs $listeners转化为响应式数据
$attrs $listeners转化为响应式数据初始化state
响应式原理
依赖类
用于记录watcher,并通知watcher更新
开始渲染组件
Watcher类
当它的依赖改变时通知watcher对象更新,更新数据或组件重新渲染
核心:
get方法,返回expOrFn的结果,并把传入的expOrFn方法或表达式中接触过的data,props中的property设为此watcher的依赖,当依赖项的setter触发时会通知watcher重新调用get方法获取新的值
stateMixin()
stateMixin()该函数给Vue实例定义了$data $props属性,全局$set $delete与$watch方法
Last updated
Was this helpful?