vue实现多页面开发
多页面应用(MPA)配置方法
在Vue CLI中配置多页面应用需要修改vue.config.js文件。每个页面需要独立的入口文件、模板和路由配置。
// vue.config.js
module.exports = {
pages: {
index: {
entry: 'src/pages/index/main.js',
template: 'public/index.html',
filename: 'index.html'
},
about: {
entry: 'src/pages/about/main.js',
template: 'public/about.html',
filename: 'about.html'
}
}
}
目录结构组织
推荐的项目目录结构应清晰区分不同页面的资源:
src/
├── pages/
│ ├── index/
│ │ ├── main.js
│ │ ├── App.vue
│ │ └── components/
│ └── about/
│ ├── main.js
│ ├── App.vue
│ └── components/
├── assets/
└── public/
├── index.html
└── about.html
公共代码处理
共享的组件和工具可以放在公共目录中:
// 在页面入口文件中引入公共依赖
import Vue from 'vue'
import CommonComponent from '../../components/CommonComponent.vue'
构建配置优化
通过配置可以优化多页面构建:
module.exports = {
chainWebpack: config => {
config.optimization.splitChunks({
chunks: 'all',
cacheGroups: {
vendors: {
name: 'chunk-vendors',
test: /[\\/]node_modules[\\/]/,
priority: -10,
chunks: 'initial'
},
common: {
name: 'chunk-common',
minChunks: 2,
priority: -20,
chunks: 'initial',
reuseExistingChunk: true
}
}
})
}
}
页面间跳转处理
由于是多页面应用,需要使用常规链接而非Vue Router:
<!-- 在模板中使用常规a标签 -->
<a href="/about.html">跳转到关于页</a>
开发服务器配置
确保开发服务器能正确处理多页面路由:
module.exports = {
devServer: {
historyApiFallback: {
rewrites: [
{ from: /^\/index/, to: '/index.html' },
{ from: /^\/about/, to: '/about.html' }
]
}
}
}
静态资源处理
静态资源路径需要根据部署环境配置:
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/your-project-name/'
: '/'
}
生产环境部署
构建后会生成多个HTML文件,需要确保服务器正确配置路由:
npm run build
# 输出目录结构
dist/
├── index.html
├── about.html
└── static/






