vue路由实现his
vue路由实现his
Vue Router 默认使用 hash 模式,但可以通过配置切换到 history 模式(his),即基于 HTML5 History API 的路由。以下是实现 history 模式的关键步骤:
配置路由模式
在创建 Vue Router 实例时,设置 mode 为 'history':
const router = new VueRouter({
mode: 'history',
routes: [...]
})
服务器端配置
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>
前端部署注意事项
- 确保静态资源路径正确,可通过设置
publicPath解决。 - 避免直接访问嵌套路由时返回 404,需依赖服务器配置。
处理 404 页面 添加通配符路由捕获未匹配路径:
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})
开发环境配置
若使用 webpack-dev-server,需设置 historyApiFallback:
devServer: {
historyApiFallback: true
}
注意事项
- 需要支持 History API 的现代浏览器(IE9 及以下不支持)。
- SEO 友好性优于 hash 模式,但需确保服务器正确配置。
- 生产环境部署时,需清除浏览器缓存以避免旧路由策略冲突。







