Vue.js 2中移除Vue Router URL的#符号问题求助
解决VueRouter History模式下的路由失效与资源加载问题
核心问题根源
开启history模式后,浏览器刷新会直接向服务器请求domain/main.html/路径,但服务器默认无对应资源,因此返回404;资源加载失败则多是因为使用相对路径,路由切换后资源基准路径发生变化。
分步解决方案
1. 配置服务器回退规则
根据你使用的服务器类型,设置所有请求都指向main.html:
- Nginx:在配置文件的
location块中添加location / { try_files $uri $uri/ /main.html; } - Apache:在项目根目录创建
.htaccess文件,写入<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /main.html [L] </IfModule> - Vue CLI开发服务器:在
vue.config.js中配置module.exports = { devServer: { historyApiFallback: { index: '/main.html' } } }
2. 修复资源加载路径
- 将项目中图片、脚本、样式等资源的路径改为绝对路径,或在
vue.config.js中配置publicPath:module.exports = { publicPath: './' // 也可设置为项目根路径,如 '/your-project/' } - 确保路由
base配置匹配部署路径:const router = new VueRouter({ mode: 'history', base: '/main.html/', routes })
3. 调整通配路由规则
将通配路由改为直接渲染首页组件,避免刷新时的路径冲突:
{ path: '*', component: Home } // Home为你的首页组件
内容的提问来源于stack exchange,提问作者Harsh Shukla
相关产品推荐
相关产品推荐

