关于vue.js:一招解决Vue多页面路由history模式开发到部署

6次阅读

共计 1652 个字符,预计需要花费 5 分钟才能阅读完成。

开启多页面模式

module.exports = {pages: {},
}

官网文档 - 多页面配置

路由模式

const mainRoutes = [
    {
        path: "/",
        name: "main",
        component: Layout,
        redirect: "/home",
        children: [
            {
                path: "/home",
                name: "home",
                component: () => import("@/html/sysadmin/views/home/home"),
                meta: {title: "home",},
            },
        ],
    },
];

const router = new Router({
    mode: "history", // 配置 history 模式
    base: "/sysadmin", // 取个利用门路名字
    routes: mainRoutes,
});

官网文档 -vue-Router base

开发模式

vue.config.js

增加以下配置

publicPath:'/', // 留神 publicPath 的门路是斜杠
configureWebpack: {
        devServer: {
            historyApiFallback: {
                verbose: true,
                rewrites: [{ from: /^\/index\/.*$/, to: "/index.html"}, 
                    {from: /^\/sysadmin\/.*$/, to: "/sysadmin.html"}
                ],
            },
        },
    },

线上 nginx 模式

打包目录

配置 nginx

server {
        listen       9041;
        server_name  pb5;
        client_max_body_size 500m;

        location / {
            root   /usr/local/dist;
            index  index.html index.htm;
        }
        
        location ^~ /api { # api 接口代理
            rewrite  ^/api/(.*)$ /$1 break;
            proxy_set_header Host $host:9041;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
            proxy_pass http://192.168.10.38:8080; # 内网 IP
            
        }
        
        # 留神 nginx 的执行程序是先匹配的 /sysadmin 的,而后再匹配 /
        
        location /sysadmin { # 这里的配置就是相当于配置了个门路,而后 nginx 做了一层拦挡
             root   /usr/local/dist;
             index sysadmin.html;
             try_files $uri $uri/ /sysadmin.html;
        }
    }

如果你的我的项目是二级目录, 须要这样配置,比照看下不同店

location / { # 根目录
            root   /usr/local/dist;
            index  index.html index.htm;
        }
location  ^~/sysadmin{
        roxy_redirect  off; # 如果是域名须要关上,ip 不须要
        alias   /usr/local/dist/sysadmin; # 二级目录 
        index  index.html index.htm;    
        try_files $uri $uri/ /sysadmin/index.html;            
}

解释

对于 alias 能够这篇文章

$uri 这个是 nginx 的一个变量,寄存着用户拜访的地址, 比方:http://xxx.com/sysadmin/sysadmin.html,$uri 就是 sysadmin.html

$uri/ 代表拜访的是一个目录,比方:http://xxx.com/sysadmin/requirelist/,那么 $uri/ 就是 /sysadmin/requirelist/

nginx 中 try_files 的含意:try_files 会去尝试到网站目录读取用户拜访的文件,如果第一个变量存在,就间接返回;不存在持续读取第二个变量,如果存在,间接返回;不存在间接跳转到第三个参数上。

正文完
 0