vue路由中,history和hash两种模式有什么区别?
参考答案
区别
| 维度 | hash 模式 | history 模式 |
|---|---|---|
| URL 形态 | https://a.com/#/user | https://a.com/user |
| 实现 | location.hash + hashchange 事件 | history.pushState/replaceState + popstate 事件 |
| 服务端配置 | 不需要(# 后不发请求) | 需要 rewrite 到 index.html,否则刷新 404 |
| 页面刷新 | 正常 | 需要服务端兜底 |
| SEO | 不利于抓取(# 后内容常被忽略) | 路径干净,利于 SEO |
| 兼容性 | 全兼容(含老浏览器) | 需要 History API(IE10+),部分旧环境受限 |
| 长度限制 | 受 URL 总长限制 | 同 |
| 美观 | # 较丑 | 干净 |
| 与后端路由冲突 | 不冲突 | 需协调(/api 等前缀要排除) |
| 部署难度 | 低 | 中(Nginx/Apache/静态托管都要配 fallback) |
机制细节
- hash:改
location.hash不触发页面请求,浏览器只滚动锚点并触发hashchange;pushState不可用时也能回退。 - history:
pushState改变 URL 不刷新,但浏览器前进后退会触发popstate;pushState不会触发popstate,所以路由内部要自己调用更新逻辑(Vue Router 已处理)。
命名
Vue Router 4 用 createWebHashHistory() / createWebHistory();history 模式还支持 createWebHistory('/base/') 指定 base。
部署配套
location / {
try_files $uri $uri/ /index.html;
}
选择
- 内部系统/兼容性优先 → hash(零配置);
- 对外产品/需要 SEO/追求 URL 美观 → history(配好服务端 fallback);
- 静态托管(GitHub Pages 等无法配 rewrite)→ hash 或预渲染。