}
Install解析 (对应目录结构的install.js)
该方法内主要做了以下三件事:
1、对Vue实例混入beforeCreate钩子操作(在Vue的生命周期阶段会被调用)
2、通过Vue.prototype定义router、router、route 属性(方便所有组件可以获取这两个属性)
3、Vue上注册router-link和router-view两个组件
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({
//对Vue实例混入beforeCreate钩子操作
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.prototype定义$router、$route 属性(方便所有组件可以获取这两个属性)
Object.defineProperty(Vue.prototype, '$router', {
get () { return this._routerRoot._router }
})
Object.defineProperty(Vue.prototype, '$route', {
get () { return this._routerRoot._route }
})
//Vue上注册router-link和router-view两个组件
Vue.component('RouterView', View)
Vue.component('RouterLink', Link)
const strats = Vue.config.optionMergeStrategies
// use the same hook merging strategy for route hooks
strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created
}
第二步 生成router实例
const router = new VueRouter({
routes
})生成实例过程中,主要做了以下两件事
1、根据配置数组(传入的routes)生成路由配置记录表。
2、根据不同模式生成监控路由变化的History对象
注:History类由HTML5History、HashHistory、AbstractHistory三类继承
history/base.js实现了基本history的操作
history/hash.js,history/html5.js和history/abstract.js继承了base,只是根据不同的模式封装了一些基本操作
第三步 生成vue实例
const app = new Vue({
router,
template: `
<div id="app">
<h1>Basic</h1>
<ul>
<li><router-link to="/">/</router-link></li>
<li><router-link to="/user">用户</router-link></li>










