【vue-router 源码01】入口处

93 阅读1分钟

src/index.js

export default class VueRouter

VueRouter.install = install // => 指向/src/install.js

src/install.js

export let _Vue
export function install(Vue) {
    if (install.installed && _Vue === Vue) return
    install.installed = true
    _Vue = Vue
    // 保证挂载一次
    
    const isDef = v => v !== undefined
    const registerInstance = (vm, callVal) => {
        let i = vm.$options._parentVnode
        if (isDef(i) && isDef((i = i.data)) && isDef((i = i.registerRouteInstance))) {
            i(vm, callVal)
        }
    }
    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)
        }
    })
    // 根实例初始化router,beforeCreate 延组件逐层传递_routerRoot,_route包裹响应,registerInstance 在<router-view />中注册/清空vue实例
    
    Object.defineProperty(Vue.prototype, '$router', {
        get() { return this._routerRoot._router }
    })

    Object.defineProperty(Vue.prototype, '$route', {
        get() { return this._routerRoot._route }
    })
    // 随_routerRoot逐层传递$router => _router,$route => _route => _router.history.current
    
    Vue.component('RouterView', View)
    Vue.component('RouterLink', Link)
    // 注册特有组件
    
    const strats = Vue.config.optionMergeStrategies
    strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created
    // 定义合并策略与created相同
}
  • 保证挂载一次
  • 根实例初始化router,beforeCreate 延组件逐层传递_routerRoot,_route包裹响应,registerInstance 在<router-view />中注册/清空vue实例
  • 随_routerRoot逐层传递 $router => _router$route => _route => _router.history.current
  • 注册特有组件
  • 定义合并策略与created()相同