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

18次阅读

共计 3873 个字符,预计需要花费 10 分钟才能阅读完成。

前言

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

正文完
 0