vue实现路由历史
Vue 路由历史模式实现
Vue Router 提供两种路由模式:hash 模式和 history 模式。history 模式基于 HTML5 History API,URL 更加简洁(无 # 符号),但需要服务器配置支持。
启用 history 模式
在 Vue Router 配置中设置 mode: 'history':
import { createRouter, createWebHistory } from 'vue-router';
const router = createRouter({
history: createWebHistory(), // Vue 3 使用 createWebHistory
routes: [...]
});
服务器配置示例
Nginx 配置
确保所有路由请求重定向到 index.html:
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>
注意事项
-
后端支持:需确保服务器正确处理 404 情况,否则刷新非首页路由会返回 404。
-
静态资源路径:若项目部署在子路径(如
/app/),需配置publicPath和路由的base选项:createWebHistory('/app/') // Vue 3 子路径 -
SEO 友好:
history模式对搜索引擎更友好,但需配合服务端渲染(SSR)或预渲染优化动态内容。
回退方案
若无法配置服务器,可降级为 hash 模式:
createWebHashHistory() // Vue 3 的 hash 模式






