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)
}
})
Object.defineProperty(Vue.prototype, '$router', {
get () { return this._routerRoot._router }
})
Object.defineProperty(Vue.prototype, '$route', {
get () { return this._routerRoot._route }
})
读源码可知$route
其实就是根组件$root
的_route
属性, 他并没有定义在data里, 而是调用Vue.util.defineReactive(this, '_route', this._router.history.current)
, 该方法只会监听_route
这个对象的最表层, 也就是_route
被赋值=xxx, 才会触发响应式监听被watch到.
相反,定义在data里的数据在组件被实例化时
initData (vue.esm.js?115c:4762)
initState (vue.esm.js?115c:4668)
Vue._init (vue.esm.js?115c:5015)
在initData
时会被深度地响应式化