乐趣区

JS每日一题:new Vue()中发生了什么?

20190214 问
new Vue() 中发生了什么?
先从语法上分析,new 关键字在 js 语言中代表实例化一个对象, 而 Vue 实际上是一个类, 我们简单看一下源码
源码地址 https://github.com/vuejs/vue/…

// 从源码可以看到 vue 类中非常干净,只是执行了一个_init 私有函数, 并且只能通过 new 关键字初始化
function Vue (options) {
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)
}
接着我们追踪至_init 函数
源码地址 https://github.com/vuejs/vue/…

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)
initRender(vm)
callHook(vm, ‘beforeCreate’)
initInjections(vm) // resolve injections before data/props
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)
}
}
}
从上面的代码我们看见_init 很清淅的干了几件事, 合并相关配置, 初始化生命周期,初始化事件中心,初始化渲染,初始化 data、props、computed、watcher 等
题外话
Vue 初始化逻辑非常清淅,把不同的功能拆成一些单独的函数执行,这种思想值得借鉴和学习
关于 JS 每日一题
JS 每日一题可以看成是一个语音答题社区 每天利用碎片时间采用 60 秒内的语音形式来完成当天的考题 群主在次日 0 点推送当天的参考答案
注 绝不仅限于完成当天任务,更多是查漏补缺,学习群内其它同学优秀的答题思路
点击加入答题

退出移动版