vue实现多个页面
实现多页面的基础配置
在Vue项目中实现多页面应用(MPA)需要修改webpack配置。Vue CLI默认生成的是单页面应用(SPA),需通过vue.config.js自定义配置。
// vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
pages: {
index: {
entry: 'src/main.js',
template: 'public/index.html',
filename: 'index.html'
},
page2: {
entry: 'src/page2/main.js',
template: 'public/page2.html',
filename: 'page2.html'
}
}
})
创建独立入口文件
每个页面需要独立的入口文件。例如创建src/page2/main.js:
import Vue from 'vue'
import App from './App.vue'
new Vue({
render: h => h(App)
}).$mount('#app')
对应的App.vue应放在同级目录:
<template>
<div id="app">
<h1>Page 2 Content</h1>
</div>
</template>
配置HTML模板
在public目录下创建对应HTML模板文件(如page2.html):

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Page 2</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
路由配置方案
对于需要前端路由的页面,可单独配置路由:
// src/page2/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(Router)
export default new Router({
routes: [
{ path: '/', component: Home }
]
})
在入口文件中引入路由:
// src/page2/main.js
import router from './router'
new Vue({
router,
render: h => h(App)
}).$mount('#app')
构建与部署
运行构建命令会自动生成多个HTML文件:

npm run build
输出目录结构示例:
dist/
├── index.html
├── js/
├── css/
├── page2.html
开发环境调试
启动开发服务器时,可通过不同URL访问各页面:
http://localhost:8080/index.html
http://localhost:8080/page2.html
公共代码优化
通过webpack的splitChunks配置共享公共依赖:
// vue.config.js
module.exports = {
configureWebpack: {
optimization: {
splitChunks: {
chunks: 'all'
}
}
}
}






