第一步:在build/utils/webpack.prod.conf.js 中的output中添加一条 publicPath:’./’
- 在build/utils/webpack.prod.conf.js 中的output中添加一条 publicPath:’./'
如果有则继续往下走,come on!!! 没有的话看第二步 Vue-cli3.0文件配置
- Vue-cli3.0没有config文件,需要自己在根目录新建一个vue.config.js文件。具体内容如下:
const webpack = require("webpack");
module.exports = {
publicPath:'./', <-- 写成'./'
};
第二步:router/index.js路由模式
- 一定要设置一个 不要不写 虽然默认的是 mode:‘hash’ 但不写的话会造成访问时出现空白页面 一定要写上 默认的hash模式会有# ,找到目录src/router/index.js 修改成如下图所示:
2.vue hash模式下,URL中存在’#’,用’history’模式就能解决这个问题。
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: resolve => require(['../views/Main/main'], resolve) ,
}
但是history模式会出现刷新页面后,页面出现404。解决的办法是用nginx配置一下。
方法一:
server {
listen 9010;
server_name localhost;
location /{
root F:/mxr/WebApp/mxr/unpackage/dist/build/h5/;
index index.html index.htm;
if (!-e $request_filename) {
rewrite ^/(.*) /index.html last;
break;
}
}
}
方法二:
server {
listen 9010;#默认端口是80,如果端口没被占用可以不用修改
server_name localhost;
root F:/mxr/WebApp/mxr/unpackage/dist/build/h5/;#vue项目的打包后的dist
location / {
try_files $uri $uri/ @router;#需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404
index index.html index.htm;
}
#对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
#因此需要rewrite到index.html中,然后交给路由在处理请求资源
location @router {
rewrite ^.*$ /index.html last;
}
}
vue.js官方教程里提到的https://router.vuejs.org/zh/guide/essentials/history-mode.html#后端配置例子
然后测试刷新就OK啦!