vue的路由实现模式
Vue 路由实现模式
Vue Router 提供了两种路由实现模式:Hash 模式和History 模式。两者在 URL 表现形式、兼容性和服务器配置方面有所不同。

Hash 模式
Hash 模式利用 URL 中的哈希部分(#)实现路由切换,无需服务器额外配置。

- URL 示例:
http://example.com/#/home - 特点:
- 哈希后的内容不会发送到服务器,完全由前端控制。
- 兼容性极佳,支持所有浏览器(包括 IE9)。
- 无需服务器配置,适合静态部署。
- 配置方式:
const router = new VueRouter({ mode: 'hash', routes: [...] })
History 模式
History 模式基于 HTML5 History API(pushState/replaceState),URL 更简洁,但需服务器支持。
- URL 示例:
http://example.com/home - 特点:
- URL 无哈希,更美观。
- 需服务器配置,避免直接访问子路由时返回 404。
- 兼容性稍差(不支持 IE9 及以下)。
- 配置方式:
const router = new VueRouter({ mode: 'history', routes: [...] })
服务器配置示例
若使用 History 模式,需在服务器配置重定向规则:
- Nginx:
location / { try_files $uri $uri/ /index.html; } - Apache:
RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]
选择建议
- 若项目需兼容老旧浏览器或静态部署,选择 Hash 模式。
- 若追求美观 URL 且能控制服务器配置,选择 History 模式。






