import router from './router'new Vue({ el: '#app', router, render: h => h(App)}) 引入router后,router实例为什么要挂载到vue根组件上?
告诉Vue, 引入 Router 了。 用了debugger,走了一遍流程,也读了源代码: 当: const app = new Vue({ router }).$mount('#app') Vue会把router传入 $options 中 然后当使用 Vue.install(VueRouter)时候 实际上会定义一个 Mixin,mixin会定义两个生命周期函数。 当 beforeCreate 触发的时候,如果 this.$options.router 存在,就会注入一个 this._router 的变量。 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, 引入 Router 了。
用了debugger,走了一遍流程,也读了源代码:
当:
Vue会把router传入 $options 中
然后当使用
Vue.install(VueRouter)
时候实际上会定义一个 Mixin,mixin会定义两个生命周期函数。
当
beforeCreate
触发的时候,如果this.$options.router
存在,就会注入一个 this._router 的变量。