前端深度——Vue-router 模式 hash | history | abstract 的区别

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第4天,点击查看活动详情

Vue-router 模式

题目

Vue-router 模式 'hash' | 'history' | 'MemoryHistory(abstract)' 的区别

v4 的升级

Vue-router v4 升级之后,mode: 'xxx' 替换为 API 的形式,但功能是一样的

  • mode: 'hash' 替换为 createWebHashHistory()
  • mode: 'history' 替换为 createWebHistory()
  • mode: 'abstract' 替换为 createMemoryHistory()

PS:个人感觉,叫 memory 比叫 abstract 更易理解,前者顾名思义,后者就过于抽象。

import { createRouter, createMemoryHistory } from 'vue-router'
import Home from '../views/Home.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = createRouter({
  history: createMemoryHistory(),
  routes
})

export default router

复制代码

hash

// http://127.0.0.1:8881/hash.html?a=100&b=20#/aaa/bbb
location.protocol // 'http:'
location.hostname // '127.0.0.1'
location.host // '127.0.0.1:8881'
location.port // '8881'
location.pathname // '/hash.html'
location.search // '?a=100&b=20'
location.hash // '#/aaa/bbb'
复制代码

hash 的特点

  • 会触发页面跳转,可使用浏览器的“后退” “前进”
  • 但不会刷新页面,支持 SPA 必须的特性
  • hash 不会被提交到 server 端(因此刷新页面也会命中当前页面,让前端根据 hash 处理路由)

url 中的 hash ,是不会发送给 server 端的。前端 onhashchange 拿到自行处理。

// 页面初次加载,获取 hash
document.addEventListener('DOMContentLoaded', () => {
    console.log('hash', location.hash)
})
// hash 变化,包括:
// a. JS 修改 url
// b. 手动修改 url 的 hash
// c. 浏览器前进、后退
window.onhashchange = (event) => {
    console.log('old url', event.oldURL)
    console.log('new url', event.newURL)

    console.log('hash', location.hash)
}
复制代码

H5 history API

常用的两个 API

  • history.pushState
  • window.onpopstate

页面刷新时,服务端要做处理,可参考文档。。即无论什么 url 访问 server ,都要返回该页面。

按照 url 规范,不同的 url 对应不同的资源,例如:

  • https://github.com/ server 返回首页
  • https://github.com/username/ server 返回用户页
  • https://github.com/username/project1/ server 返回项目页

但是用了 SPA 的前端路由,就改变了这一规则,假如 github 用了的话:

  • https://github.com/ server 返回首页
  • https://github.com/username/ server 返回首页,前端路由跳转到用户页
  • https://github.com/username/project1/ server 返回首页,前端路由跳转到项目页

所以,从开发者的实现角度来看,前端路由是一个违反规则的形式。 但是从不关心后端,只关心前端页面的用户,或者浏览器来看,更喜欢 pushState 这种方式。

三种模式的区别

  • hash - 使用 url hash 变化记录路由地址
  • history - 使用 H5 history API 来改 url 记录路由地址
  • abstract - 不修改 url ,路由地址在内存中,但页面刷新会重新回到首页

连环问:react-router 有几种模式?

react-router 有三种模式,设计上和 vue-router 一样

猜你喜欢

转载自juejin.im/post/7086275132842311687