]});
//new Vue 启动
new Vue({
el: '#app',
//让vue知道我们的路由规则
router: router, //可以简写router
render: c => c(App),
})
最后记得在在app.vue中“留坑”
//app.vue中
<template>
<div>
<!-- 留坑,非常重要 -->
<router-view></router-view>
</div>
</template>
<script>
export default {
data(){
return {}
}
}
</script>vue-router源码分析
我们先来看看vue的实现路径。

在入口文件中需要实例化一个 VueRouter 的实例对象 ,然后将其传入 Vue 实例的 options 中。
export default class VueRouter {
static install: () => void;
static version: string;
app: any;
apps: Array<any>;
ready: boolean;
readyCbs: Array<Function>;
options: RouterOptions;
mode: string;
history: HashHistory | HTML5History | AbstractHistory;
matcher: Matcher;
fallback: boolean;
beforeHooks: Array<?NavigationGuard>;
resolveHooks: Array<?NavigationGuard>;
afterHooks: Array<?AfterNavigationHook>;
constructor (options: RouterOptions = {}) {
this.app = null
this.apps = [] this.options = options
this.beforeHooks = [] this.resolveHooks = [] this.afterHooks = [] // 创建 matcher 匹配函数
this.matcher = createMatcher(options.routes || [], this)
// 根据 mode 实例化具体的 History,默认为'hash'模式
let mode = options.mode || 'hash'
// 通过 supportsPushState 判断浏览器是否支持'history'模式
// 如果设置的是'history'但是如果浏览器不支持的话,'history'模式会退回到'hash'模式
// fallback 是当浏览器不支持 history.pushState 控制路由是否应该回退到 hash 模式。默认值为 true。
this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false
if (this.fallback) {
mode = 'hash'
}
// 不在浏览器内部的话,就会变成'abstract'模式
if (!inBrowser) {
mode = 'abstract'
}
this.mode = mode
// 根据不同模式选择实例化对应的 History 类
switch (mode) {
case 'history':
this.history = new HTML5History(this, options.base)
break
case 'hash':
this.history = new HashHistory(this, options.base, this.fallback)
break
case 'abstract':
this.history = new AbstractHistory(this, options.base)










