Vue路由的两种模式:hash模式与history模式详解和对比
Vue的路由实现有hash模式、history 模式和abstract 模式。根据mode 参数来决定采用哪一种方式。
hash: 使用 URL hash 值来作路由。默认模式。
history: 依赖 HTML5 History API 和服务器配置。查看 HTML5 History 模式
export default new Router({
mode: 'history',
routes: [
{
path: '/about',
name: 'about',
component: () => import('@/components/About.vue')
},
{
path: '/',
name: 'home',
component: () => import('@/components/Home.vue')
}
]
})
hash模式
Hash 模式是 Vue Router 默认的路由模式,在这种模式下,URL 中会包含一个带有 # 符号的哈希部分,例如
http://localhost:8088/#/home
工作原理
Hash 模式基于浏览器的 window.location.hash 属性。当 URL 中的哈希部分发生变化时,Vue Router 会监听到这个变化,并相应地切换视图。
优点:
兼容性: