vue多页面实现
Vue 多页面应用实现方法
Vue 通常用于单页面应用(SPA),但通过配置可以实现多页面应用(MPA)。以下是具体实现方式:
修改 webpack 配置
在 vue.config.js 中配置多个入口文件:
module.exports = {
pages: {
index: {
entry: 'src/pages/index/main.js',
template: 'public/index.html',
filename: 'index.html'
},
page2: {
entry: 'src/pages/page2/main.js',
template: 'public/page2.html',
filename: 'page2.html'
}
}
}
目录结构调整
创建多页面目录结构:
src/
pages/
index/
main.js
App.vue
page2/
main.js
App.vue
公共代码处理
在 src 下创建 common 文件夹存放公共组件和工具:
src/
common/
components/
utils/
路由配置
每个页面使用独立的路由配置:
// src/pages/index/router.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: '/',
name: 'home',
component: Home
}
]
})
构建配置优化
在 vue.config.js 中添加优化配置:
module.exports = {
configureWebpack: {
optimization: {
splitChunks: {
chunks: 'all',
minSize: 10000,
maxSize: 250000
}
}
}
}
开发环境配置
修改 package.json 脚本:
{
"scripts": {
"serve": "vue-cli-service serve --open",
"build": "vue-cli-service build",
"build:index": "vue-cli-service build --page index",
"build:page2": "vue-cli-service build --page page2"
}
}
静态资源处理
在 public 文件夹中为每个页面创建独立的 HTML 模板:
public/
index.html
page2.html
部署注意事项
部署时需要确保服务器正确配置多页面路由,避免 404 错误。Nginx 配置示例:

location / {
try_files $uri $uri/ /index.html;
}
location /page2 {
try_files $uri $uri/ /page2.html;
}
这种方法允许每个页面拥有独立的 Vue 实例、路由和状态管理,适合需要完全隔离的多页面场景。






