大前端時代我們都習慣把模塊盡可能的拆的比較細,這樣方便維護起來比較方便,找起來也很容易。
微信官方已經給出了模板的引用,
<template name="title">
<view class='container'>
<view class='title'></view>
</view>
</template>
在需要的地方導入,引用
<import src="../template/index/block.wxml"/>
<template is="title"/>
wxss當中也只需要
@import "../template/index/block.wxss"
但在js邏輯中,看到很多人大多是通過module.exports的方式導出一個模塊,然后在需要用的地方require某個模塊,然后在某個生命周期函數中調用這個模塊的某個方法。但這樣模塊之間的耦合仍然很大,並不能實現真正的拆分。熟悉vue的同學一定會了解mixin,但微信官方並沒有給出方案,所以就自己寫了一個,僅供參考。
建一個utils的文件夾,文件夾下建一個utils.js,內容如下
module.exports.mixinModule = function() {
let tempModel = {}
let targetModel = {}
for (let model in arguments) {
for (let data in arguments[model]) {
let l = arguments[model]
if (tempModel[data] == undefined) {
tempModel[data] = []
}
tempModel[data].push(l[data])
}
}
for (let key in tempModel) {
if (typeof tempModel[key][0] == "object") {
targetModel[key] = {}
for (let tempKey in tempModel[key]) {
Object.assign(targetModel[key], tempModel[key][tempKey])
}
} else if (typeof tempModel[key][0] == "function") {
targetModel[key] = function () {
for (let func of tempModel[key]) {
func()
}
}
}
}
return targetModel;
}
比如我們現在的模塊是block.js,在onReady里彈出一個toast,就隨便舉一個例子,大家可以在里面寫自己的業務邏輯
// pages/type/index.js
module.exports = {
/**
* 頁面的初始數據
*/
data: {
},
/**
* 生命周期函數--監聽頁面加載
*/
onLoad: function (options) {
},
/**
* 生命周期函數--監聽頁面初次渲染完成
*/
onReady: function () {
wx.showToast({
title: '成功',
icon: 'success',
duration: 2000
})
},
/**
* 生命周期函數--監聽頁面顯示
*/
onShow: function () {
},
/**
* 生命周期函數--監聽頁面隱藏
*/
onHide: function () {
},
/**
* 生命周期函數--監聽頁面卸載
*/
onUnload: function () {
},
/**
* 頁面相關事件處理函數--監聽用戶下拉動作
*/
onPullDownRefresh: function () {
},
/**
* 頁面上拉觸底事件的處理函數
*/
onReachBottom: function () {
},
/**
* 用戶點擊右上角分享
*/
onShareAppMessage: function () {
}
}
比如說在index.js里要用這個模塊,那么只需要調這個方法把兩個模塊混合進來
var block = require("../template/index/block.js")
var mixinUtil = require("../../utils/util.js")
let page = {
/**
* 頁面的初始數據
*/
data: {
},
/**
* 生命周期函數--監聽頁面加載
*/
onLoad: function (options) {
},
/**
* 生命周期函數--監聽頁面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函數--監聽頁面顯示
*/
onShow: function () {
},
/**
* 生命周期函數--監聽頁面隱藏
*/
onHide: function () {
},
/**
* 生命周期函數--監聽頁面卸載
*/
onUnload: function () {
},
/**
* 頁面相關事件處理函數--監聽用戶下拉動作
*/
onPullDownRefresh: function () {
},
/**
* 頁面上拉觸底事件的處理函數
*/
onReachBottom: function () {
},
/**
* 用戶點擊右上角分享
*/
onShareAppMessage: function () {
}
}
Page(mixinUtil.mixinModule(page,block));
這樣就實現了功能的一個拆分