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


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

相关推荐
刺客xs1 分钟前
Qt-----QSS样式表
开发语言·javascript·qt
m0_7400437312 分钟前
3、Vuex-Axios-Element UI
前端·javascript·vue.js
阿蒙Amon17 分钟前
JavaScript学习笔记:14.类型数组
javascript·笔记·学习
风止何安啊18 分钟前
一场组件的进化脱口秀——React从 “类” 到 “hooks” 的 “改头换面”
前端·react.js·面试
JS_GGbond18 分钟前
给数组装上超能力:JavaScript数组方法趣味指南
前端·javascript
前端无涯19 分钟前
Tailwind CSS v4 开发 APP 内嵌 H5:安卓 WebView 样式丢失问题解决与降级实战
前端
小邋遢2.021 分钟前
vscod 执行npm build报错:Error: Cannot find module ‘vite‘
前端·npm·node.js
OLong21 分钟前
this有且仅有的五种指法
javascript
是你的小橘呀22 分钟前
新手入门 React 必备:电影榜单项目核心知识点全解析
前端·javascript
yinmaisoft23 分钟前
JNPF 钉钉双向同步攻略:组织 / 用户一键打通,触发事件自动联动
前端·低代码·钉钉