部属vue项目,访问路径设置非根,显示白屏的解决方案
发布时间:2023-05-15 05:12:31
若部署Vue项目时设置了访问路径非根路径,如:http://example.com/vueapp,则可能会出现白屏问题。这个问题的解决方案有以下两种:
1. 使用Vue Router的base属性
在Vue Router中,可以通过设置base属性来指定项目的根路径,如:
const router = new VueRouter({
mode: 'history',
base: '/vueapp/',
routes: ...
})
这样,即使访问 http://example.com/vueapp 实际访问的也是/app/下的路由,而不是根路径下的路由。
2. 修改Nginx或Apache配置文件
如果使用的是Nginx或Apache作为服务器,可以通过修改它们的配置文件来解决该问题。
对于Nginx来说,可以在server段中添加以下配置:
location /vueapp/ {
alias /path/to/vueapp/;
try_files $uri $uri/ /vueapp/index.html;
}
其中,/path/to/vueapp/为Vue项目打包后的目录路径。
对于Apache来说,可以在.htaccess文件中添加以下配置:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /vueapp/
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /vueapp/index.html [L]
</IfModule>
其中,RewriteBase /vueapp/指定了项目的根路径,RewriteRule . /vueapp/index.html [L]表示如果请求的文件或目录不存在,则重定向到index.html页面。
通过以上两种方法可以解决部署Vue项目时访问路径设置非根时出现的白屏问题。需要注意的是,如果采用 种方法,要确保Vue项目中所有使用到路由的地方,如:路由链接和动态路由的路径等,都需要添加base路径。
