【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那么方便


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

相关推荐
早點睡39014 分钟前
ReactNative项目OpenHarmony三方库集成实战:react-native-dropdown-picker
javascript·react native·react.js
升鲜宝供应链及收银系统源代码服务7 小时前
《IntelliJ + Claude Code + Gemini + ChatGPT 实战配置手册升鲜宝》
java·前端·数据库·chatgpt·供应链系统·生鲜配送
i建模7 小时前
将Edge浏览器的标签页从顶部水平排列**移至左侧垂直侧边栏
前端·edge
跟着珅聪学java8 小时前
js编写中文转unicode 教程
前端·javascript·数据库
英俊潇洒美少年8 小时前
Vue3 深入响应式系统
前端·javascript·vue.js
颜酱8 小时前
回溯算法实战练习(3)
javascript·后端·算法
英俊潇洒美少年9 小时前
React 最核心 3 大底层原理:Fiber + Diff + 事件系统
前端·react.js·前端框架
我命由我123459 小时前
React Router 6 - 概述、基础路由、重定向、NavLink、路由表
前端·javascript·react.js·前端框架·ecmascript·html5·js
LJianK19 小时前
java封装
java·前端·数据库
yaaakaaang9 小时前
(四)前端,如此简单!---Promise
前端·javascript