vue-cli 3.x 多頁面配置
一、前言
1. 單頁面(SPA Single-Page-Application)
(1)入口:單頁面只是一張 Web 頁面的模式,只有一個 html 檔案,整個專案只有一個入口檔案。
(2)資源載入:單頁面應用的資源只在開始初始化進入的的時候載入一次(屬於全域性載入使用),之後的元件跳轉不再重新載入。專案初始化壓力較大。
(3)頁面跳轉:單頁面內的頁面跳轉其實是 vue 運用了 vue-router 實現了元件切換。
(4)資料傳遞:可通過全域性變數、引數或 store 進行資料互動。
2. 多頁面(MPA Multi-Page-Application)
(1)入口:多頁面是多張 web 頁面的模式,有多個 html 檔案,整個專案有多個入口檔案。
(2)資源載入:多頁面之間的資源互不影響,npm 依賴包是全域性安裝,但是在多頁面每個入口檔案(main.js)手動按需引入。多頁面之間資源互不共享,跳轉需要資源重新載入,專案初始化壓力較小,但多頁面之間跳轉資源需重新載入,壓力相對較大。
(3)頁面跳轉:多頁面的單個頁面內部是 vue-router 形式的元件切換;多頁面之間需通過 a 標籤跳轉頁面。
(4)資料傳遞:多頁面的單個頁面內部和 SPA 一致;多頁面之間需通過位址列傳參形式進行資料互動。
圖源:https://blog.csdn.net/bandaoyu/article/details/104563959
二、配置
1. 新建專案 demo
(1)通過 vue-cli 3.x
新建專案(vue create demo),刪除專案中自帶的 App.vue
和 main.js
(2)安裝 path
和 glob
依賴包(npm i path -D 、npm i glob -D)
2. 配置入口檔案
(1) 在 src
目錄下新建 pages
用於配置多頁面模組的資料夾。
(2)在 pages
資料夾下新建多頁面模組,在此舉慄 home
和 index
資料夾。
(3)在多頁面的模組下(home
和 index
),分別新建 App.vue
和 main.js
,按原有的內容填充這兩個檔案,用於每個頁面模組的入口。
<!-- * @Date: 2020-12-01 13:53:49 * @information: App.vue --> <template> <div id="app"> <router-view/> </div> </template> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; } </style>
/*
* @Date: 2020-12-01 13:53:55
* @information: main.js
*/
import Vue from 'vue'
import App from './App.vue'
import router from '../../router/home'
import store from '../../store'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
3. 新增全域性啟動和打包配置
(1)在專案根目錄下新建 vue.config.js
配置檔案
(2)新增入口宣告配置 和 打包配置,具體如下:
/*
* @Date: 2020-12-01 11:35:31
* @information: vue.config.js
*/
const path = require('path')
const glob = require('glob')
const titles = {
home: '這是home標題',
index: '這是index標題'
}
// 獲取pages資料夾下的檔案
function getEntry(globPath) {
let entries = {}, tmp;
// 讀取js檔案
glob.sync(globPath+'js').forEach(function(entry) {
tmp = entry.split('/').splice(-3)
entries[tmp[1]] = {
entry,
template: 'index.html',
filename: tmp[1] + '.html',
title: titles[tmp[1]],
}
})
return entries
}
const htmls = getEntry('./src/pages/**/*.')
module.exports = {
pages: htmls,
publicPath: './',
outputDir: 'dist', // 打包後的資料夾名稱,預設dist
devServer: {
open: true,
hot: true,
index: './index.html', // 預設啟動頁面
host: '0.0.0.0',
port: 8090,
},
productionSourceMap: false, // 生產環境是否生成 sourceMap 檔案
}
三、爬坑注意
1. 專案目錄劃分
(1)將 components
、router
、views
、store
、靜態資料配置層、業務層等檔案結構按照多頁面模組嚴格劃分,多頁面之間不容有業務上的耦合,防止進坑。
(2)對於每個頁面模組所用到的資源按需引入,減輕模組載入壓力。
2. 專案目錄及打包的 html 檔案如圖
專案 pages 資料夾
專案打包後的多頁面生成的 html 檔案