# vue的初始化
_init
方法中,经过 mergeOptions
合并处理选项之后,执行下面这段代码
if (process.env.NODE_ENV !== 'production') {
//非生产环境 在core/instance/proxy.js
initProxy(vm)
} else {
vm._renderProxy = vm
}
//
// 声明 initProxy 变量
let initProxy
const hasProxy =typeof Proxy !== 'undefined' && Proxy.toString().match(/native code/)//是否原生支持proxy
if (process.env.NODE_ENV !== 'production') {
// ... 其他代码
// 在这里初始化 initProxy
initProxy = function initProxy (vm) {
if (hasProxy) {
// determine which proxy handler to use
const options = vm.$options
const handlers = options.render && options.render._withStripped//_withStripped一般为假
? getHandler
: hasHandler
vm._renderProxy = new Proxy(vm, handlers)
} else {
vm._renderProxy = vm
}
}
}
const hasHandler = {
has (target, key) {
const has = key in target
const isAllowed = allowedGlobals(key) || key.charAt(0) === '_' //_开头的字符串,或者在allowedGlobals 内
if (!has && !isAllowed) {
warnNonPresent(target, key)//打印错误
}
return has || !isAllowed
}
}
// 导出
export { initProxy }
//目的就是设置渲染函数的作用域代理,其目的是为我们提供更好的提示信息
_init
在执行完initProxy
后,就是initLifecycle
unction initLifecycle (vm: Component) {
// 定义 options,它是 vm.$options 的引用,后面的代码使用的都是 options 常量
const options = vm.$options
//将当前实例添加到父实例的 $children 属性里,并设置当前实例的 $parent 指向父实例
// locate first non-abstract parent
//定义 parent,它引用当前实例的父实例
let parent = options.parent
//当前实例不是抽象的
if (parent && !options.abstract) {
//while 循环查找第一个非抽象的父组件
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent
}
//parent 应该是一个非抽象的组件,将它作为当前实例的父级,所以将当前实例 vm 添加到父级的 $children 属性里
parent.$children.push(vm)
}
//设置当前实例的 $parent 属性,指向父级
vm.$parent = parent
// $root 属性,有父级就是用父级的 $root,否则 $root 指向自身
vm.$root = parent ? parent.$root : vm
vm.$children = []
vm.$refs = {}
vm._watcher = null
vm._inactive = null
vm._directInactive = false
vm._isMounted = false
vm._isDestroyed = false
vm._isBeingDestroyed = false
}
initEvents
function initEvents (vm: Component) {
vm._events = Object.create(null)
vm._hasHookEvent = false
// init parent attached events
const listeners = vm.$options._parentListeners
if (listeners) {
updateComponentListeners(vm, listeners)
}
}
initRender
function initRender (vm: Component) {
vm._vnode = null // the root of the child tree
vm._staticTrees = null // v-once cached trees
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
// bind the createElement fn to this instance
// so that we get proper render context inside it.
// args order: tag, data, children, normalizationType, alwaysNormalize
// internal version is used by render functions compiled from templates
vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
// normalization is always applied for the public version, used in
// user-written render functions.
vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)
// $attrs & $listeners are exposed for easier HOC creation.
// they need to be reactive so that HOCs using them are always updated
const parentData = parentVnode && parentVnode.data
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
//defineReactive 函数,该函数的作用就是为一个对象定义响应式的属性
defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, () => {
!isUpdatingChildComponent && warn(`$attrs is readonly.`, vm)
}, true)
defineReactive(vm, '$listeners', options._parentListeners || emptyObject, () => {
!isUpdatingChildComponent && warn(`$listeners is readonly.`, vm)
}, true)
} else {
defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, null, true)
defineReactive(vm, '$listeners', options._parentListeners || emptyObject, null, true)
}
}
initRender
执行完之后代码
callHook(vm, 'beforeCreate')//调用生命周期钩子
//initState 包括了:initProps、initMethods、initData、initComputed 以及 initWatch。
//所以当 beforeCreate 钩子被调用时,所有与 props、methods、data、computed 以及 watch 相关的内容都不能使用,
//当然了 inject/provide 也是不可用的。
initInjections(vm) // resolve injections before data/props
initState(vm)
initProvide(vm) // resolve provide after data/props
callHook(vm, 'created')
function callHook (vm: Component, hook: string) {
// #7573 disable dep collection when invoking lifecycle hooks
pushTarget()
const handlers = vm.$options[hook]
if (handlers) {
for (let i = 0, j = handlers.length; i < j; i++) {
try {
handlers[i].call(vm)
} catch (e) {
handleError(e, vm, `${hook} hook`)
}
}
}
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook)
}
popTarget()
}
function initState (vm: Component) {
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 {
//不存在data,observe 函数观测一个空对象:{}。
observe(vm._data = {}, true /* asRootData */)
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch && opts.watch !== nativeWatch) {//nativeWatch firefox有watch
initWatch(vm, opts.watch)
}
}