关于vue-router:vuerouter源码一routerinstall解析

前言

【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办法,在卸载之前重置一些属性、删除一些监听函数

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理