前言
【vue-router源码】系列文章将带你从0开始理解vue-router
的具体实现。该系列文章源码参考vue-router v4.0.15
。
源码地址:https://github.com/vuejs/router
浏览该文章的前提是你最好理解vue-router
的根本应用,如果你没有应用过的话,可通过vue-router官网学习下。
该篇文章首先介绍router.install
的过程。
vue-router的应用
在介绍router.install
之前,咱们先看下vue3
中是如何应用vue-router
的。
import { createApp } from 'vue'
import { createRouter } from 'vue-router'
const router = createRouter({ ... })
const app = createApp({})
app.use(router).mount('#app')
在执行app.use
的过程中,会执行router.install
,并传入app
实例。那么router.install
过程中产生了什么呢?接下来咱们一探到底。
router.install
router.install
源码位于createRouter
中,文件地位src/router.ts
。
install(app: App) {
const router = this
app.component('RouterLink', RouterLink)
app.component('RouterView', RouterView)
app.config.globalProperties.$router = router
Object.defineProperty(app.config.globalProperties, '$route', {
enumerable: true,
get: () => unref(currentRoute),
})
if (
isBrowser &&
!started &&
currentRoute.value === START_LOCATION_NORMALIZED
) {
started = true
push(routerHistory.location).catch(err => {
if (__DEV__) warn('Unexpected error when starting the router:', err)
})
}
const reactiveRoute = {} as {
[k in keyof RouteLocationNormalizedLoaded]: ComputedRef<
RouteLocationNormalizedLoaded[k]
>
}
for (const key in START_LOCATION_NORMALIZED) {
reactiveRoute[key] = computed(() => currentRoute.value[key])
}
app.provide(routerKey, router)
app.provide(routeLocationKey, reactive(reactiveRoute))
app.provide(routerViewLocationKey, currentRoute)
const unmountApp = app.unmount
installedApps.add(app)
app.unmount = function () {
installedApps.delete(app)
if (installedApps.size < 1) {
pendingLocation = START_LOCATION_NORMALIZED
removeHistoryListener && removeHistoryListener()
removeHistoryListener = null
currentRoute.value = START_LOCATION_NORMALIZED
started = false
ready = false
}
unmountApp()
}
if ((__DEV__ || __FEATURE_PROD_DEVTOOLS__) && isBrowser) {
addDevtools(app, router, matcher)
}
}
在install
中,首先会注册RouterLink
与RouterView
两大组件。
app.component('RouterLink', RouterLink)
app.component('RouterView', RouterView)
而后会将以后的router
对象赋值给app.config.globalProperties.$router
;同时拦挡了app.config.globalProperties.$route
的get
操作,使app.config.globalProperties.$route
始终获取unref(currentRoute)
,unref(currentRoute)
就是以后路由的一些信息,这里咱们先不深究,在后续章节中会具体介绍。这样一来,就能够在组件中通过this.$router
获取router
,通过this.$route
来获取以后路由信息。
app.config.globalProperties.$router = router
Object.defineProperty(app.config.globalProperties, '$route', {
enumerable: true,
get: () => unref(currentRoute),
})
紧接着会依据浏览器url地址进行第一次跳转(如果是浏览器环境)。
if (
isBrowser &&
// 用于初始导航客户端,防止在多个利用中应用路由器时屡次push
!started &&
currentRoute.value === START_LOCATION_NORMALIZED
) {
started = true
push(routerHistory.location).catch(err => {
if (__DEV__) warn('Unexpected error when starting the router:', err)
})
}
紧接着申明了一个reactiveRoute
响应式对象,并遍历START_LOCATION_NORMALIZED
对象,顺次将START_LOCATION_NORMALIZED
中的key
复制到reactiveRoute
中,同时将reactiveRoute
中key
对应的值变成一个计算属性。
这里START_LOCATION_NORMALIZED
是vue-router
提供的初始路由地位,通过START_LOCATION_NORMALIZED
构建一个响应式的路由reactiveRoute
,不便对路由变动进行追踪。
const reactiveRoute = {} as {
[k in keyof RouteLocationNormalizedLoaded]: ComputedRef<
RouteLocationNormalizedLoaded[k]
>
}
for (const key in START_LOCATION_NORMALIZED) {
reactiveRoute[key] = computed(() => currentRoute.value[key])
}
app.provide(routerKey, router)
app.provide(routeLocationKey, reactive(reactiveRoute))
app.provide(routerViewLocationKey, currentRoute)
这里应用provide
又将router
、currentRoute
注入到app
实例中,你可能会疑难,在后面过程中曾经能够在组件中应用this.$router
、this.$route
获取到对应数据了,这里为什么又应用provide
再次注入呢?这是因为在setup
中式无法访问this
的,这时通过inject
就能够不便获取router
及currentRoute
。
最初会将app
放入一个哈希表中,而后重写app.unmount
。当app
卸载时,首先从哈希表中删除app
,而后判断哈希表的大小是否小于1,如果小于1代表曾经没有实例应用vue-router
了,那么这时就须要重置一些状态、移除一些监听。
const unmountApp = app.unmount
installedApps.add(app)
app.unmount = function () {
installedApps.delete(app)
if (installedApps.size < 1) {
pendingLocation = START_LOCATION_NORMALIZED
removeHistoryListener && removeHistoryListener()
removeHistoryListener = null
currentRoute.value = START_LOCATION_NORMALIZED
started = false
ready = false
}
unmountApp()
}
总结
通过上述剖析,router.install
次要做以下几件事:
- 注册
RouterLink
、RouterView
组件 - 设置全局属性
$router
、$route
- 依据地址栏进行首次的路由跳转
- 向
app
中注入一些路由相干信息,如路由实例、响应式的以后路由信息对象 - 拦挡
app.unmount
办法,在卸载之前重置一些属性、删除一些监听函数
发表回复