返回

Vue+Vite 多页应用配置及页面路径更改指南

前端

多页应用概述

多页应用(MPA)是一种在单页面应用(SPA)的基础上扩展的架构,它包含多个独立的页面,每个页面都有自己的 URL 和状态。这种架构更适合于内容丰富的网站或具有复杂导航的应用程序。

Vue+Vite 多页应用配置

1. 安装依赖项

npm install vite vue

2. 创建项目

vite create vite-mpa

3. vite.config.js 配置

// vite.config.js
module.exports = {
  plugins: [
    vue({
      template: {
        compilerOptions: {
          isCustomElement: (tag) => tag.startsWith('my-')
        }
      }
    })
  ],
  build: {
    rollupOptions: {
      input: {
        main: 'index.html',
        page1: 'page1.html',
        page2: 'page2.html',
        ...
      }
    }
  }
};

4. index.html 主页面

<!-- index.html -->
<div id="app">
  <router-view></router-view>
</div>

5. 页面文件

<!-- page1.html -->
<template>
  <h1>Page 1</h1>
</template>

<script>
export default {
  name: 'Page1'
};
</script>

页面路径更改

默认情况下,Vue+Vite 会使用文件路径作为页面路由。要更改页面路径,可以在 router.js 中自定义路由配置:

// router.js
import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    {
      path: '/page1',
      component: () => import('./page1.vue')
    },
    {
      path: '/page2',
      component: () => import('./page2.vue')
    }
  ]
});

export default router;

目录优化

对于大型多页应用,可以对目录进行优化以提高性能:

1. 代码分割

// main.js
import('./page1').then((module) => {
  const Page1 = module.default;
  // ...
});

2. 预加载

<!-- index.html -->
<link rel="preload" as="script" href="page1.js">

3. 惰性加载

// router.js
import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    {
      path: '/page1',
      component: () => import(/* webpackChunkName: "page1" */ './page1.vue')
    },
    {
      path: '/page2',
      component: () => import(/* webpackChunkName: "page2" */ './page2.vue')
    }
  ]
});

export default router;

注意点

  • 多页应用的 SEO 优化需要额外关注。
  • 使用服务器端渲染可以进一步提高性能。
  • 确保为每个页面配置正确的元数据。