likes
comments
collection
share

【vue-router源码】一、router.install解析

作者站长头像
站长
· 阅读数 37

前言

【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中,首先会注册RouterLinkRouterView两大组件。

app.component('RouterLink', RouterLink)
app.component('RouterView', RouterView)

然后会将当前的router对象赋值给app.config.globalProperties.$router;同时拦截了app.config.globalProperties.$routeget操作,使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中,同时将reactiveRoutekey对应的值变成一个计算属性。

这里START_LOCATION_NORMALIZEDvue-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又将routercurrentRoute注入到app实例中,你可能会疑问,在前面过程中已经可以在组件中使用this.$routerthis.$route获取到对应数据了,这里为什么又使用provide再次注入呢?这是因为在setup中式无法访问this的,这时通过inject就可以方便获取routercurrentRoute

最后会将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主要做以下几件事:

  1. 注册RouterLinkRouterView组件
  2. 设置全局属性$router$route
  3. 根据地址栏进行首次的路由跳转
  4. app中注入一些路由相关信息,如路由实例、响应式的当前路由信息对象
  5. 拦截app.unmount方法,在卸载之前重置一些属性、删除一些监听函数