vue3+vite项目搭建多页结构

383 阅读1分钟

虽然现在单页应用居多,但是多页应用的配置咱也得会,这里以vite+vue3项目为例,参考Vite提供的多页应用配置(vite官网文档说明)。我自己搭建了一个多页结构,步骤如下:

假设我现在的目录结构如下:

image.png

1.以index.html为例,需要注意html文件里要引入对应的js模块:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + Vue</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/views/IndexPage/main.js"></script>
  </body>
</html>

2.index.html对应的页面组件App.vue:

<script setup>
</script>
<template>
  <div>这是首页,<a href="video.html">点击这里</a> 可以跳转到视频页面</div>
</template>
<style scoped>
</style>

3.index.html对应的入口文件main.js

import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

4.vite.config.js配置

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  build: {
    rollupOptions: {
      input: {
        index: resolve(__dirname, './public/index.html'),
        video: resolve(__dirname, './public/video.html'),
      },
    },
  }
})

5.执行命令 npm run dev ,访问:

image.png

6.也可以给某一个页面配置多个路由:先安装 npm i vue-router -S

再创建 src/views/IndexPage/router/index.js

import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
const router = createRouter({
    history: import.meta.env.DEV ? createWebHashHistory() : createWebHistory(),
    routes: [
        {
            path: '/',
            redirect: '/hot'
        },
        {
            path: '/hot',
            component: () => import('../components/HotMovie.vue')
        },
    ]
})
export default router

7.在src/views/IndexPage/mian.js中引入并注册router

import { createApp } from 'vue'
import App from './App.vue'
import router from './router' // 引入路由
const app = createApp(App)
// 注册路由
app.use(router).mount('#app')

8.在src/views/IndexPage/App.vue中添加路由占位符

// ……
<template>
  <router-view></router-view>
</template>
// ……

9.然后就可以通过http://localhost:5173/index.html#/hot 访问了