router实例为什么要挂载到vue根组件上?

import router from './router'
new Vue({
el: '#app',
router,
render: h => h(App)
})

引入router后,router实例为什么要挂载到vue根组件上?

阅读 6.8k
2 个回答

告诉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)
    }
  })

官方文档就这么要求的,你又不需要去深究源码,你只要知道这么写,下面使用的所有组件,都能访问this.$router这个对象就行了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题