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