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 uidvm._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 observedvm._isVue = true// merge optionsif (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 selfvm._self = vminitLifecycle(vm)initEvents(vm)initRender(vm)callHook(vm, 'beforeCreate')initInjections(vm) // resolve injections before data/propsinitState(vm)initProvide(vm) // resolve provide after data/propscallHook(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点推送当天的参考答案
- 注 绝不仅限于完成当天任务,更多是查漏补缺,学习群内其它同学优秀的答题思路
点击加入答题