Vue-router source code first reading

 

Why must a installmethod be defined and assigned to it VueRouter? In fact, this is Vue.userelated to the method. Do you still remember how Vue uses VueRouter?

import VueRouter from 'vue-router'

Vue.use(VueRouter) // 第一步

export default new VueRouter({ // 传入的options
    routes // 第二步
})

import router from './router'

new Vue({
  router,  // 第三步
  render: h => h(App)
}).$mount('#app')

In fact, the second and third steps are very clear, which is to instantiate a VueRouter object and hang this VueRouter object on the root component App. Then the question comes, what is the purpose of Vue.use(VueRouter) in the first step? In fact , it is the method of Vue.use(XXX)execution , that is, Vue.use(VueRouter) === VueRouter.install() , but at this point, we know that it will be executed, but we still don’t know what it is for and what is the use of it. ?XXXinstallinstallinstall

We know that the VueRouter object is attached to the root component App, so the App can directly use the methods on the VueRouter object, but we know that we must want to use the methods of VueRouter, for example, but now only the 每一个用到的组件App this.$router.pushcan What to do with these methods? How can every component be used? At this time install, the method comes in handy. Let's talk about the implementation idea first, and then write the code.

 

How does vue-router realize that each vue component can access $router, and it is realized by writing mix-in in vue install

Screenshot 2021-09-25 pm 10.20.09.png

 

const VueRouter = {}
// eslint-disable-next-line no-unused-vars
var _vue
export default VueRouter.install = (Vue) => {
  _vue = Vue
  // 使用Vue.mixin混入每一个组件
  Vue.mixin({
    // 在每一个组件的beforeCreate生命周期去执行
    beforeCreate() {
      if (this.$options.myRouter) {
        // this 是 根组件本身
        this._myrouterRoot = this
        this.myRouter = this.$options.myRouter
      } else {
        // 非根组件,也要把父组件的_routerRoot保存到自身身上
        this._myrouterRoot = this.$parent && this.$parent.myRouter
        // 子组件也要挂上$router
        this.myRouter = this._myrouterRoot
      }
    }
  })
}

Guess you like

Origin blog.csdn.net/qq_27449993/article/details/121121061