Vue-router 中 hash 和 html5 两种路由监听方式

vue-router 的两种路由方式

如果你用过 Vue,那你一定知道 vue-router,它给开发者提供了两种路由方式

hash 模式

hash 模式是用 createWebHashHistory() 创建的:

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

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

HTML5 模式

createWebHistory() 创建 HTML5 模式路由:

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

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

不同模式的路由监听方式

这两种不同模式的路由方式,它们对路由的监听方式也不同

hash 模式监听方式

window.addEventListener('hashchange', () => {
    
    
	console.log('触发 hash 路由变化')
})

HTML5 模式监听方式

  • history.gohistory.backhistory.forward 使用 popstate 事件
  • pushStatereplaceState 需要通过函数重写的方式进行劫持
window.addEventListener('popstate', () => {
    
    
	console.log('触发 popstate 路由变化')
})

const rawPushState = window.history.pushState
window.history.pushState = (...args) => {
    
    
	rawPushState.apply(window.history, args)
	console.log('劫持到 pushState 变化了')
}

const rawReplaceState = window.history.replaceState
window.history.replaceState = (...args) => {
    
    
	rawReplaceState.apply(window.history, args)
	console.log('劫持到 replaceState 变化了')
}

猜你喜欢

转载自blog.csdn.net/weixin_43443341/article/details/128034106
今日推荐