const app = new Vue({
router,
store
}).$mount('#app')
上面实例话vue对象时为什么可以传入的router和store对象,在什么时候使用呢
保存的位置
new vue其实是调用源码中下面的方法
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)
}
也就是说router和store这种参数是保存在options参数中的。
使用
在vue-router源码的install方法中有如下代码
Vue.mixin({
beforeCreate () {
if (isDef(this.$options.router)) {
this._routerRoot = this
this._router = this.$options.router
this._router.init(this)
Vue.util.defineReactive(this, '_route', this._router.history.current)
} else {
this._routerRoot = (this.$parent && this.$parent._routerRoot) || this
}
registerInstance(this, this)
},
destroyed () {
registerInstance(this)
}
})
在VUE root component中可以通过this.$options.router取到new vue传入的options对象
这里还有一个技巧
如何使所有子组件都取到vue跟组件初始化的对象,比如这里的this._routerRoot。关键是this.$parent