浅析vue-router原理

2020-06-12 21:21:45易采站长站整理

break
default:
if (process.env.NODE_ENV !== 'production') {
assert(false, `invalid mode: ${mode}`)
}
}
}
match (
raw: RawLocation,
current?: Route,
redirectedFrom?: Location
): Route {
return this.matcher.match(raw, current, redirectedFrom)
}
get currentRoute (): ?Route {
return this.history && this.history.current
}
init (app: any /* Vue component instance */) {
process.env.NODE_ENV !== 'production' && assert(
install.installed,
`not installed. Make sure to call `Vue.use(VueRouter)` ` +
`before creating root instance.`
)
this.apps.push(app)
// main app already initialized.
if (this.app) {
return
}
this.app = app
const history = this.history
// 根据history的类别执行相应的初始化操作和监听
if (history instanceof HTML5History) {
history.transitionTo(history.getCurrentLocation())
} else if (history instanceof HashHistory) {
const setupHashListener = () => {
history.setupListeners()
}
history.transitionTo(
history.getCurrentLocation(),
setupHashListener,
setupHashListener
)
}
history.listen(route => {
this.apps.forEach((app) => {
app._route = route
})
})
}
// 路由跳转之前
beforeEach (fn: Function): Function {
return registerHook(this.beforeHooks, fn)
}
// 路由导航被确认之间前
beforeResolve (fn: Function): Function {
return registerHook(this.resolveHooks, fn)
}
// 路由跳转之后
afterEach (fn: Function): Function {
return registerHook(this.afterHooks, fn)
}
// 第一次路由跳转完成时被调用的回调函数
onReady (cb: Function, errorCb?: Function) {
this.history.onReady(cb, errorCb)
}
// 路由报错
onError (errorCb: Function) {
this.history.onError(errorCb)
}
// 路由添加,这个方法会向history栈添加一个记录,点击后退会返回到上一个页面。
push (location: RawLocation, onComplete?: Function, onAbort?: Function) {
this.history.push(location, onComplete, onAbort)
}
// 这个方法不会向history里面添加新的记录,点击返回,会跳转到上上一个页面。上一个记录是不存在的。
replace (location: RawLocation, onComplete?: Function, onAbort?: Function) {
this.history.replace(location, onComplete, onAbort)
}
// 相对于当前页面向前或向后跳转多少个页面,类似 window.history.go(n)。n可为正数可为负数。正数返回上一个页面
go (n: number) {
this.history.go(n)
}
// 后退到上一个页面
back () {
this.go(-1)
}
// 前进到下一个页面
forward () {