Vue Router 的 History 模式 和 Hash 模式 是两种不同的路由实现方式,主要区别如下:
1. URL 表现形式不同
// Hash 模式
http://example.com/#/user/profile
// URL 中带有 # 符号
// History 模式
http://example.com/user/profile
// URL 看起来更自然,没有 # 符号
2. 实现原理不同
Hash 模式:
-
基于
window.location.hash和onhashchange事件 -
只改变 URL 中 # 后面的部分,不会触发页面刷新
-
不会将 URL 发送到服务器
// 改变 hash
window.location.hash = '/user'// 监听变化
window.addEventListener('hashchange', () => {
console.log('hash changed:', window.location.hash)
})
History 模式:
-
基于 HTML5 History API(pushState、replaceState)
-
可以修改完整的 URL 而不刷新页面
-
需要服务器端配合
// 添加历史记录
history.pushState({}, '', '/user')// 替换当前历史记录
history.replaceState({}, '', '/user')
3. 服务器配置要求
Hash 模式:
-
不需要服务器特殊配置
-
因为 # 后面的内容不会被发送到服务器
-
部署简单,所有路由都指向同一个 HTML 文件
History 模式:
-
需要服务器配置
-
用户直接访问或刷新子路由时,服务器会返回 404
-
需要配置所有路径都返回 index.html
Nginx 配置示例
location / {
try_files uri uri/ /index.html;
}
4. 兼容性
-
Hash 模式:兼容性更好,支持 IE8+
-
History 模式:需要 IE10+ 或现代浏览器支持
5. SEO 友好性
-
Hash 模式:不利于 SEO,# 后面的内容传统爬虫不会抓取
-
History 模式:对 SEO 更友好,URL 完整可被爬虫识别
6. 配置方式
// router/index.js
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
// Hash 模式
const router = createRouter({
history: createWebHashHistory(),
routes: [...]
})
// History 模式
const router = createRouter({
history: createWebHistory(),
routes: [...]
})
使用建议
-
使用 Hash 模式:
-
简单项目或 demo
-
没有服务器配置权限
-
需要兼容低版本浏览器
-
不关心 SEO
-
-
使用 History 模式:
-
需要干净的 URL
-
需要 SEO 支持
-
有服务器配置权限
-
现代浏览器项目
-
注意事项
-
使用 History 模式时,确保服务器已正确配置
-
两种模式在开发环境下通常都能正常工作,差异主要在部署时
-
Vue Router 会自动根据模式使用相应的底层 API