以下表格总结了这两种路由方式的实现方式、特性和适用场景。
| 路由模式 | 实现方式 | URL 表现形式 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|---|---|
| Hash 模式 | 使用 URL 的 hash (#) 部分实现,通过 window.location.hash 监听 URL 变化。 | http://example.com/#/path | 兼容性好,不需要服务器配置。 | URL 中有 #,不够美观。 | 兼容性要求高、无需服务器配置的场景。 |
| History 模式 | 使用 HTML5 的 history.pushState() 和 history.replaceState() 实现,依赖浏览器 History API | http://example.com/path | URL 结构清晰,符合标准 URL 规范,利于 SEO。 | 需要服务器支持,在刷新时需正确路由配置。 | SEO 友好、服务器支持 HTML5 History 的场景。 |
详细实现方式
Hash 模式
-
在 Vue Router 配置中指定
mode: 'hash':import { createRouter, createWebHashHistory } from 'vue-router'; const router = createRouter({ history: createWebHashHistory(), routes: [ { path: '/', component: Home }, { path: '/about', component: About }, ], }); -
Hash 模式通过 URL
#后面的部分识别路由路径,页面不会重新加载。
History 模式
-
在 Vue Router 配置中指定
mode: 'history':import { createRouter, createWebHistory } from 'vue-router'; const router = createRouter({ history: createWebHistory(), routes: [ { path: '/', component: Home }, { path: '/about', component: About }, ], }); -
History 模式需要服务器支持 URL 重写,否则页面刷新时会产生 404 错误。一般的配置示例如下:
- Nginx 配置示例:
location / { try_files $uri $uri/ /index.html; } - Apache 配置示例(
.htaccess文件):<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule>
- Nginx 配置示例:
总结
- Hash 模式 适用于快速开发、无需复杂服务器配置的项目。
- History 模式 更适合需要 SEO 支持、对 URL 美观度要求较高的项目。