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


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

相关推荐
大数据追光猿11 分钟前
Python中的Flask深入认知&搭建前端页面?
前端·css·python·前端框架·flask·html5
莫忘初心丶14 分钟前
python flask 使用教程 快速搭建一个 Web 应用
前端·python·flask
横冲直撞de1 小时前
前端接收后端19位数字参数,精度丢失的问题
前端
我是哈哈hh1 小时前
【JavaScript进阶】作用域&解构&箭头函数
开发语言·前端·javascript·html
摸鱼大侠想挣钱1 小时前
ActiveX控件
前端
谢尔登1 小时前
Vue 和 React 响应式的区别
前端·vue.js·react.js
酷酷的阿云1 小时前
Vue3性能优化必杀技:useDebounce+useThrottle+useLazyLoad深度剖析
前端·javascript·vue.js
神明木佑1 小时前
HTML 新手易犯的标签属性设置错误
前端·css·html
老友@1 小时前
OnlyOffice:前端编辑器与后端API实现高效办公
前端·后端·websocket·编辑器·onlyoffice
bin91531 小时前
DeepSeek 助力 Vue 开发:打造丝滑的缩略图列表(Thumbnail List)
前端·javascript·vue.js·ecmascript·deepseek