路由模式

90 阅读1分钟

hash 模式

创建

import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    //...
  ],
})

监听 hash 变化

window.addEventListener('hashchange', (e: HashChangeEvent) => {
  console.log(e);
})

image.png

H5 模式

创建

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    //...
  ],
})

监听

window.addEventListener('popstate', (e: PopStateEvent) => {
  console.log(e);
})

image.png

跳转

history.pushState(),注意:这种方式的跳转不能被浏览器监听到,跳转后需要手动刷新页面

image.png