【Vue-Router】路由模式

1. WebHashHistory

index.ts

ts 复制代码
import { createRouter, createWebHistory, RouteRecordRaw, createWebHashHistory } from "vue-router";

// 路由模式
//vue2 mode history -> vue3 createWebHistory
//vue2 mode  hash -> vue3  createWebHashHistory
//vue2 mode abstact -> vue3  createMemoryHistory

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    component: () => import("../components/login.vue")
  },
  {
    path: "/reg",
    component: () => import("../components/reg.vue")
  }
]

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

export default router


hash实现

hash是URL中hash()及后面的那部分,常用作描点在页面内进行导航,改变URL中的hash部分不会引起页面刷新

通过hashchange事件监听URL的变化,改变URL的方式只有这几种:

  1. 通过浏览器前进后退改变URL
  2. 通过<a>标签改变URL
  3. 通过window.location改变URL


2. WebHistory

index.ts

ts 复制代码
import { createRouter, createWebHistory, RouteRecordRaw, createWebHashHistory } from "vue-router";

// 路由模式
//vue2 mode history -> vue3 createWebHistory
//vue2 mode  hash -> vue3  createWebHashHistory
//vue2 mode abstact -> vue3  createMemoryHistory

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    component: () => import("../components/login.vue")
  },
  {
    path: "/reg",
    component: () => import("../components/reg.vue")
  }
]

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

export default router


history实现

history提供了pushState和replaceState两个方法,这两个方法改变URL的path部分不会引起页面刷新

history提供类似hashchange事件的popstate事件,但popstate事件有些不同:

  1. 通过浏览器前进后退改变URL时会触发popstate事件
  2. 通过pushState/replaceState或<a>标签改变URL不会触发popstate事件
  3. 好在我们可以拦藏pushState/replaceState的调用和<a>标签的点击事件来检测URL变化
  4. 通过js调用history的back,go,forward方法触发该事件

所以监听URL变化可以实现,只是没有hashchange那么方便


但此时切换路径后并不会被监听,需要刷新页面

相关推荐
人工智能训练师4 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny074 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy5 小时前
css的基本知识
前端·css
昔人'5 小时前
css `lh`单位
前端·css
前端君5 小时前
实现最大异步并发执行队列
javascript
Nan_Shu_6146 小时前
Web前端面试题(2)
前端
知识分享小能手7 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
蚂蚁RichLab前端团队7 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光8 小时前
css之一个元素可以同时应用多个动画效果
前端·css
萌萌哒草头将军8 小时前
Oxc 和 Rolldown Q4 更新计划速览!🚀🚀🚀
javascript·vue.js·vite