vue的路由实现模式
Vue 路由实现模式
Vue Router 是 Vue.js 的官方路由管理器,支持两种主要的路由模式:Hash 模式和History 模式。两种模式的区别主要在于 URL 的表现形式以及服务器配置要求。
Hash 模式
Hash 模式利用 URL 的 hash(#)部分来实现路由。这种模式不需要服务器端配置,适合静态部署或无需后端支持的项目。
- URL 示例:
http://example.com/#/about - 特点:
- 改变 hash 不会触发页面刷新。
- 兼容性较好,支持旧版浏览器。
- 服务器无需额外配置,直接返回
index.html即可。
配置方式:
const router = new VueRouter({
mode: 'hash',
routes: [...]
})
History 模式
History 模式基于 HTML5 History API(pushState 和 replaceState),URL 更简洁,但需要服务器支持。
- URL 示例:
http://example.com/about - 特点:
- URL 无
#,更美观。 - 需要服务器配置,确保所有路径返回
index.html。 - 刷新或直接访问子路由时可能返回 404,需后端配合。
- URL 无
配置方式:
const router = new VueRouter({
mode: 'history',
routes: [...]
})
服务器配置示例
- 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 模式。
两种模式在 Vue Router 中的切换仅需修改 mode 选项,其余路由逻辑保持一致。







