美文网首页Vue
vue构建多页面应用以及history模式下nginx配置

vue构建多页面应用以及history模式下nginx配置

作者: 糖小羊儿 | 来源:发表于2021-03-11 16:12 被阅读0次

在实际开发中,我们会分为前台页面和后台管理页面,或者pc端和mobile端,一般情况不会放在一个目录里面,此时我们需要使用vue构建多页面应用

1.构建多页面应用步骤

github地址

1.1 文件目录

在src里面新建pages文件夹,在pages文件夹里面新建index和admin文件夹,然后在文件夹里面新建一套单独的文件体系,里面的文件用法写法和单页面应用的写法一致。

image.png

1.2 在vue.config.js中加入:

module.exports = {
  pages: {
    'index': {
      entry: 'src/pages/index/main.js', //index 的入口文件
      filename: 'index.html', //打包之后的命名
      template: 'public/index.html',//依赖的html文件,我都用public的index,也可以定制化开发
      title: '首页page',
    },
    'admin': {
      entry: 'src/pages/admin/main.js',
      filename: 'admin/index.html',
      template: 'public/index.html',//或者 public/admin.html,需要自己手动建admin.html
      title: '管理页page',
    }
},

2.使用history模式,配置步骤

2.1 配置路由

注意base写法

//index 路由配置
export default new VueRouter({
    mode:'history',
    base:'/index/', //注意这里
    routes: routes
})
//admin 路由配置
export default new VueRouter({
    mode:'history',
    base:'/admin/',//注意这里
    routes: routes
})

2.2 配置nginx

vue项目使用history模式,打包之后,会出现404,所以我们需要后台配合才能够正常访问,这里我使用nginx做例子

server {
    listen 9914;
    server_name localhost;
    root 'F:\ui_code\多页面应用\dist';
    location / {
        index index.html;
        try_files $uri $uri/ /index.html; 
    }
    location /admin {
        index index.html;
        try_files $uri $uri/ /admin/index.html;
    }
}

3.项目处于二级目录时,配置步骤

github地址
以上的项目,发布之后的访问目录时:http://localhost/admin/home
我们如果项目需要这样访问:http://localhost/app/admin/home, 那我们就需要配置二级目录app

3.1 配置vue.config.js

module.exports = {
    publicPath: '/app/',
    outputDir: 'dist/app',
    pages: {
        'app/index': {
            entry: 'src/pages/index/main.js',
            filename: 'index.html',
            template: 'public/index.html',
            title: '首页page',
        },
        'app/admin': {
            entry: 'src/pages/admin/main.js',
            filename: 'admin/index.html',
            template: 'public/index.html',
            title: '管理页page',
        }
    },
}

3.2 配置路由

//index 路由配置
export default new VueRouter({
    mode:'history',
    base:'/app/index/', //注意这里
    routes: routes
})
//admin 路由配置
export default new VueRouter({
    mode:'history',
    base:'/app/admin/',//注意这里
    routes: routes
})

3.3 配置nginx

server {
    listen 9925;
    server_name localhost;
    root 'F:\ui_code\多页面应用有前缀\dist';
    location / app {
        index index.html;
        try_files $uri $uri/ /app/index.html;
    }
    location / app / admin {
        index index.html;
        try_files $uri $uri/ /app/admin/index.html;
    }
}

到此就可以正常使用了。

另外,我们在做项目,会用到全局配置,便于上线之后,随时可以更改,此时,我们会在public文件夹新建一个配置文件config.js,然后在index.html中引入,但是我们会遇到打包之后,此文件找不到或者报'>'错

为了解决这个问题,我们把引入的路径写成绝对路径

比如
<script src="/config"></script> 对应 http://localhost 的写法
<script src="/app/config"></script> 对应 http://localhost/app的写法

相关文章

网友评论

    本文标题:vue构建多页面应用以及history模式下nginx配置

    本文链接:https://www.haomeiwen.com/subject/uixoqltx.html