先看看源码:
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);}Vue.prototype._init = function (options) { var vm = this; ... vm.$options = mergeOptions(options || {}, vm); ... initState(vm); ... if (vm.$options.el) { vm.$mount(vm.$options.el); } ... };}
由此,不难看出做了以下步骤:
1.合并配置:
new Vue({ store: store, router: router, render: h => h(App),}).$mount('#app')//故,合并(路由、状态治理、 渲染函数)
2.初始化生命周期
function initState (vm) { vm._watchers = []; var opts = vm.$options; if (opts.props) { initProps(vm, opts.props); } if (opts.methods) { initMethods(vm, opts.methods); } if (opts.data) { initData(vm); } else { observe(vm._data = {}, true /* asRootData */); } if (opts.computed) { initComputed(vm, opts.computed); } if (opts.watch && opts.watch !== nativeWatch) { initWatch(vm, opts.watch); }}//initState就是将vue实例中的data,method,computed,watch等数据项做进一步得解决,其实就是做代理以及转化成可观测对象。
3.数据处理实现之后就将数据挂载到指定的钩子上:vm.$mount(vm.$options.el);
initLifecycle(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');
能够看到在initState(vm)执行之前,咱们执行了beforeCreate办法,在initState(vm)执行之后,咱们执行了created办法。因而在beforeCreate办法中,咱们无奈间接援用data,method,computed,watch等在initState(vm)中才开始存在的属性。