内容简介:new Vue()中发生了什么?先从语法上分析,new关键字在js语言中代表实例化一个对象, 而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点推送当天的参考答案
- 注 绝不仅限于完成当天任务,更多是查漏补缺,学习群内其它同学优秀的答题思路
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 当 Redis 发生高延迟时,到底发生了什么
- 2018年曾经发生和未曾发生的人工智能革命
- [] == ![]发生了什么?
- 安全并发之先行发生原则
- 以太坊上正在发生什么?
- 内存耗尽后 Redis 会发生什么?
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Markdown 在线编辑器
Markdown 在线编辑器
HEX CMYK 转换工具
HEX CMYK 互转工具