vue实现路由历史
Vue 路由历史模式实现
Vue Router 支持两种路由历史模式:hash 模式和 history 模式。以下是具体实现方法和注意事项。
配置路由模式
在创建 Vue Router 实例时,通过 mode 或 history 选项指定模式:
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
// history 模式
const router = createRouter({
history: createWebHistory(),
routes: [...]
})
// hash 模式
const router = createRouter({
history: createWebHashHistory(),
routes: [...]
})
模式区别
-
hash 模式
使用 URL hash 模拟完整 URL,路径格式为http://example.com/#/path
无需服务器配置,兼容性好,但 URL 不够美观
-
history 模式
使用 HTML5 History API,路径格式为http://example.com/path
URL 更简洁,但需要服务器支持以避免 404 错误
服务器配置(history 模式)
对于 history 模式,需配置服务器将所有路由重定向到 index.html:

-
Nginx
location / { try_files $uri $uri/ /index.html; } -
Apache
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule>
注意事项
使用 history 模式时,需确保后端支持前端路由
生产环境部署时,需处理静态资源路径问题
某些 CDN 可能需要额外配置以支持 history 模式






