详解如何将 Vue-cli 改造成支持多页面的 history 模式

  

下面是如何将 Vue-cli 改造成支持多页面的 history 模式的攻略。具体步骤如下:

一、创建多页面应用

首先需要在 Vue-cli 中创建多页面应用。在 src 目录下新建多个 .html 文件,比如 index.htmlabout.html 等。在 src 目录下还需要新建多个 .js 文件,比如 index.jsabout.js 等,这些 .js 文件对应着每个页面的逻辑代码。接着在 vue.config.js 文件中配置入口和模板相关

module.exports = {
  pages: {
    index: {
      // 页面入口
      entry: 'src/index.js',
      // 模板来源
      template: 'public/index.html',
      // 在 dist/index.html 的输出
      filename: 'index.html',
      // 当使用 title 选项时,
      // template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
      title: 'Index Page'
    },
    about: {
      // 页面入口
      entry: 'src/about.js',
      // 模板来源
      template: 'public/about.html',
      // 在 dist/about.html 的输出
      filename: 'about.html',
      // 当使用 title 选项时,
      // template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
      title: 'About Page'
    }
  }
}

二、配置路由

src 目录下新建 router 目录,然后在其中新建 index.js 文件来定义路由。建议使用 vue-router 来定义路由,具体的使用方法可以参考 Vue Router 官方文档。在这里只做简要介绍,以 index 页面为例:

import Vue from 'vue'
import Router from 'vue-router'
import Index from '@/views/Index'

Vue.use(Router)

export default new Router({
  mode: 'history',
  base: '/index.html',
  routes: [
    {
      path: '/',
      name: 'Index',
      component: Index
    }
  ]
})

这里我们采用了 history 模式,并在 base 中指定了当前页面的文件名,以便于在服务端配置时更好地定位。

三、配置服务端

在服务器端需要额外的配置来支持多页面的 history 模式。这里以 Nginx 服务器为例,在 nginx.conf 文件中加入以下配置:

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html;
        try_files $uri $uri/ /index.html;
    }

    location /about.html {
        root   /usr/share/nginx/html;
        index  about.html;
        try_files $uri $uri/ /about.html;
    }

    error_page  404              /404.html;
    location = /404.html {
        root   /usr/share/nginx/html;
    }
}

这样,访问 http://localhost/index.htmlhttp://localhost/about.html 就能正确地显示对应的页面了!

四、加入代码示例

下面是一个简单的示例,展示了如何将 Vue-cli 改造成支持多页面的 history 模式。这个示例项目包含了两个页面:首页和关于页。你可以下载并运行这个项目来查看具体的实现细节:

# 下载示例项目
git clone https://github.com/Liugq5713/vue-cli-multipage-demo.git

# 安装依赖
cd vue-cli-multipage-demo
npm install

# 运行项目
npm run serve

以上就是将 Vue-cli 改造成支持多页面的 history 模式的完整攻略。希望对您有所帮助!

相关文章