今天小新独自一人在家学习Vue,十分好奇上次跟小兰探讨的双向数据绑定依赖的响应式,这回他决定仔细看看是怎么回事。
让我们来看一下 new Vue()
发生了些什么:
-
new Vue()
调用构造函数创建实例this
及执行_init
,同时把options
通过new
的动作传入。function Vue(options) { if (__DEV__ && !(this instanceof Vue)) { warn('Vue is a constructor and should be called with the `new` keyword') } this._init(options) // 执行init } new Vue({ // options el: '#app', data(){ return { name: 'Vue' } } })
-
_init
初始化options
、事件、声明周期。export function initMixin(Vue: typeof Component) { Vue.prototype._init = function (options?: Record<string, any>) { const vm: Component = this // a uid vm._uid = uid++ // 给当前组件添加标识 // 初始化事件、声明周期等 initLifecycle(vm) initEvents(vm) initRender(vm) callHook(vm, 'beforeCreate', undefined, false /* setContext */) initInjections(vm) // resolve injections before data/props initState(vm) // 初始化 data initProvide(vm) // resolve provide after data/props callHook(vm, 'created') /* istanbul ignore if */ if (__DEV__ && config.performance && mark)