vue-router 路由模式探究

45 阅读1分钟

1. Location API

vue-router 路由模式的实质就是对Location和history的API进行的封装。 Location 的常用API如下:

对于链接https://example.org:8080/foo/bar?q=baz#bang

  • href 即为整个url链接;
  • search 即为?后面的参数部分;
  • hash 即为# 后面的部分;

2. History API

刷新页面的API

  • back 向后跳转,和用户点击浏览器回退按钮的效果相同;
  • forward 向前跳转,和用户点击浏览器前进按钮的效果相同;
  • go 跳转到history中指定的一个点,比如:go(-1)相当于back,go(1)相当于forward

修改历史记录的API

  • pushState 该API不会导致浏览器刷新/加载页面,只是在浏览器路由历史记录中,加上一条新的记录;
  • replaceState 该API不会导致浏览器刷新/加载页面,只是修改了当前的历史记录;

监听路由变化事件

  • popstate 当浏览器中活动的历史记录发生变化时,会触发该事件;

3. vue-router中的history模式

探究一下history模式中,push方法的实现:

push中调用的是changeLocation方法,看一下该方法的实现:

  function changeLocation(
  // 目标路由
  to: HistoryLocation,
  // 路由信息
  state: StateEntry,
  // 是否替换
  replace: boolean
): void {
  const hashIndex = base.indexOf('#')
  // 生成url
  const url =
    hashIndex > -1
      ? (location.host && document.querySelector('base')
          ? base
          : base.slice(hashIndex)) + to
      : createBaseLocation() + base + to
  try {
    // 关键,调用 replaceState 或者 pushState 
    history[replace ? 'replaceState' : 'pushState'](state, '', url)
    historyState.value = state
  } catch (err) {
    // Force the navigation, this also resets the call count
    location[replace ? 'replace' : 'assign'](url)
  }
}

再看push方法:

function push(to: HistoryLocation, data?: HistoryState) {
    // 构造目标路由
    const state: StateEntry = assign(
      {},
      buildState(currentLocation.value, to, null),
      { position: currentState.position + 1 },
      data
    )
    // 第三个参数为false,调用pushState
    changeLocation(to, state, false)
    currentLocation.value = to
  }

4. vue-router中的hash模式

hash模式是对history模式封装调用

export function createWebHashHistory(base?: string): RouterHistory {

if (!base.includes('#')) base += '#'
return createWebHistory(base)
}