好程序員web前端培訓分享kbone高級-事件系統:1、用法,對于多頁面的應用,在 Web 端可以直接通過 a 標簽或者 location 對象進行跳轉,但是在小程序中則行不通;同時 Web 端的頁面 url 實現和小程序頁面路由也是完全不一樣的,因此對于多頁開發最大的難點在于如何進行頁面跳轉。

1.1 修改 webpack 配置
對于多頁應用,此處和 Web 端一致,有多少個頁面就需要配置多少個入口文件。如下例子,這個應用中包含 page1、page2 和 page2 三個頁面:
// webpack.mp.config.js
module.exports = {
entry: {
page1: path.resolve(__dirname, '../src/page1/main.mp.js'),
page2: path.resolve(__dirname, '../src/page2/main.mp.js'),
page3: path.resolve(__dirname, '../src/page3/main.mp.js'),
},
// ... other options
}
1.2 修改 webpack 插件配置
mp-webpack-plugin 這個插件的配置同樣需要調整,需要開發者提供各個頁面對應的 url 給 kbone。
module.exports = {
origin: 'https://test.miniprogram.com',
entry: '/page1',
router: {
page1: ['/(home|page1)?', '/test/(home|page1)'],
page2: ['/test/page2/:id'],
page3: ['/test/page3/:id'],
},
// ... other options
}
其中 origin 即 window.location.origin 字段,使用 kbone 的應用所有頁面必須同源,不同源的頁面禁止訪問。entry 頁面表示這個應用的入口 url。router 配置則是各個頁面對應的 url,可以看到每個頁面可能不止對應一個 url,而且這里的 url 支持參數配置。
有了以上幾個配置后,就可以在 kbone 內使用 a 標簽或者 location 對象進行跳轉。kbone 會將要跳轉的 url 進行解析,然后根據配置中的 origin 和 router 查找出對應的頁面,然后拼出頁面在小程序中的路由,最后通過小程序 API 進行跳轉(利用 wx.redirectTo 等方法)。
2、案例
在 kbone-advanced 目錄下創建 02-mulpages 目錄。本案例在這個目錄下實現。
2.1 創建 package.json
cd 02-mulpages
npm init -y
編輯 package.json:
{
"name": "01-env",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"mp": "cross-env NODE_ENV=production webpack --config build/webpack.mp.config.js --progress --hide-modules"
},
"dependencies": {
"add": "^2.0.6",
"vue": "^2.5.11"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
],
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.0",
"cross-env": "^5.0.5",
"css-loader": "^0.28.7",
"file-loader": "^1.1.4",
"html-webpack-plugin": "^4.0.0-beta.5",
"mini-css-extract-plugin": "^0.5.0",
"optimize-css-assets-webpack-plugin": "^5.0.1",
"stylehacks": "^4.0.3",
"vue-loader": "^15.7.0",
"vue-template-compiler": "^2.6.10",
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3",
"mp-webpack-plugin": "latest"
},
"keywords": [],
"author": "",
"license": "ISC"
}
安裝依賴包:
npm install
2.2 配置 webpack
在 02-mulpages 目錄下創建 build 文件夾,在文件夾下創建 webpack.mp.config.js 文件,內容如下:
const path = require('path')
const webpack = require('webpack')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const { VueLoaderPlugin } = require('vue-loader')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin')
const MpPlugin = require('mp-webpack-plugin') // 用于構建小程序代碼的 webpack 插件
const isOptimize = false // 是否壓縮業務代碼,開發者工具可能無法完美支持業務代碼使用到的 es 特性,建議自己做代碼壓縮
module.exports = {
mode: 'production',
entry: {
page1: path.resolve(__dirname, '../src/page1/main.mp.js'),
page2: path.resolve(__dirname, '../src/page2/main.mp.js'),
page3: path.resolve(__dirname, '../src/page3/main.mp.js'),
},
output: {
path: path.resolve(__dirname, '../dist/mp/common'), // 放到小程序代碼目錄中的 common 目錄下
filename: '[name].js', // 必需字段,不能修改
library: 'createApp', // 必需字段,不能修改
libraryExport: 'default', // 必需字段,不能修改
libraryTarget: 'window', // 必需字段,不能修改
},
target: 'web', // 必需字段,不能修改
optimization: {
runtimeChunk: false, // 必需字段,不能修改
splitChunks: { // 代碼分隔配置,不建議修改
chunks: 'all',
minSize: 1000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 100,
maxInitialRequests: 100,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[/]node_modules[/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
},
minimizer: isOptimize ? [
// 壓縮CSS
new OptimizeCSSAssetsPlugin({
assetNameRegExp: /.(css|wxss)$/g,
cssProcessor: require('cssnano'),
cssProcessorPluginOptions: {
preset: ['default', {
discardComments: {
removeAll: true,
},
minifySelectors: false, // 因為 wxss 編譯器不支持 .some>:first-child 這樣格式的代碼,所以暫時禁掉這個
}],
},
canPrint: false
}),
// 壓縮 js
new TerserPlugin({
test: /.js(?.*)?$/i,
parallel: true,
})
] : [],
},
module: {
rules: [
{
test: /.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
],
},
{
test: /.vue$/,
loader: [
'vue-loader',
],
},
{
test: /.js$/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
},
exclude: /node_modules/
},
{
test: /.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
extensions: ['*', '.js', '.vue', '.json']
},
plugins: [
new webpack.DefinePlugin({
'process.env.isMiniprogram': true, // 注入環境變量,用于業務代碼判斷
}),
new MiniCssExtractPlugin({
filename: '[name].wxss',
}),
new VueLoaderPlugin(),
new MpPlugin(require('./miniprogram.config.js')),
],
}
在 02-mulpages/build 文件夾下創建 miniprogram.config.js 文件,內容如下:
module.exports = {
origin: 'https://test.miniprogram.com',
entry: '/',
router: {
page1: ['/a'],
page2: ['/b'],
page3: ['/c'],
},
redirect: {
notFound: 'page1',
accessDenied: 'page1',
},
generate: {
appEntry: 'miniprogram-app',
// 構建完成后是否自動安裝小程序依賴。'npm':使用 npm 自動安裝依賴
autoBuildNpm: 'npm'
},
runtime: {
cookieStore: 'memory',
},
app: {
navigationBarTitleText: 'kbone-multiple-pages',
},
global: {
share: true,
},
pages: {
page1: {
extra: {
navigationBarTitleText: 'page1',
},
},
},
projectConfig: {
appid: '',
projectname: 'kbone-multiple-pages',
},
packageConfig: {
author: 'Felixlu',
}
}
2.3 編寫三個頁面
在 /src/ 下創建 page1, page2, page3 三個文件夾,在文件夾里創建三個頁面,每個頁面由 App.vue 和 main.mp.js 兩個文件組成。
1、page1 頁面
/src/page1/App.vue 內容:
當前 url:{{url}}
當前頁跳轉
新開頁面跳轉
當前頁跳轉
新開頁面跳轉
.cnt {
margin-top: 20px;
}
a, button {
display: block;
width: 100%;
height: 30px;
line-height: 30px;
text-align: center;
font-size: 20px;
border: 1px solid #ddd;
}
/src/page1/main.mp.js 內容:
import Vue from 'vue'
import App from './App.vue'
export default function createApp() {
const container = document.createElement('div')
container.id = 'app'
document.body.appendChild(container)
return new Vue({
el: '#app',
render: h => h(App)
})
}
/src/common/Header.vue 內容:
wechat-miniprogram-header
.header {
margin-bottom: 10px;
width: 100%;
text-align: center;
}
/src/common/utils.js 內容:
export function printf(str) {
console.log('common/utils.js --> ', str)
}
/src/common/Footer.vue 內容:
.footer {
margin-top: 10px;
width: 100%;
text-align: center;
}
2、page2 頁面
/src/page2/App.vue 內容:
當前 url:{{url}}
回到首頁
回到首頁
relaunch
.cnt {
margin-top: 20px;
}
a, button {
display: block;
width: 100%;
height: 30px;
line-height: 30px;
text-align: center;
font-size: 20px;
border: 1px solid #ddd;
}
/src/page2/main.mp.js 內容:
import Vue from 'vue'
import App from './App.vue'
export default function createApp() {
const container = document.createElement('div')
container.id = 'app'
document.body.appendChild(container)
return new Vue({
el: '#app',
render: h => h(App)
})
}
3、page3 頁面
/src/page3/App.vue 內容:
當前 url:{{url}}
回到上一頁
關閉當前窗口
.cnt {
margin-top: 20px;
}
a, button {
display: block;
width: 100%;
height: 30px;
line-height: 30px;
text-align: center;
font-size: 20px;
border: 1px solid #ddd;
}
/src/page3/main.mp.js 內容:
import Vue from 'vue'
import App from './App.vue'
export default function createApp() {
const container = document.createElement('div')
container.id = 'app'
document.body.appendChild(container)
return new Vue({
el: '#app',
render: h => h(App)
})
}
2.4 小程序端效果預覽
npm run mp

