微信小程序組件化解決方案wx-component
前言
最近摩拜單車小程序需求越來越多,多人協作,甚至多個項目并行。如何合作的更順暢,提升團隊成員開發效率,這便是這段時間思考的問題。
其中很重要的一點就是,小程序功能組件化。但小程序的開發框架目前還不支持component,結合具體開發經驗,我們封裝了 wx-component 。
思想
靜態模板
利用微信小程序支持的 template 特性,在page中使用template去調用組件,并把組件的 methods 提升到page的屬性中去,這樣便可以在component中使用 bindtap 等綁定組件“私有”事件方法。
component和page的互相調用
在component的私有方法或onLoad等事件中,可以使用 parent 獲取page對象:
this.parent.setData({
text: "my btn text"
})
let { text } = this.parent.data
你也可以在page中使用 childrens 獲取component對象:
Page({
data: {},
components: {
login: {
text: "my login btn text",
onLogin() {
...
}
}
},
onLoad() {
this.childrens.login.setData({
text: "my text"
})
let { text } = this.childrens.login.data
}
})
props和data
在page中聲明組件依賴,可以傳入 props ,如:
Page({
data: {},
components: {
// 傳入`props`
login: {
text: "my login btn text",
onLogin() {
...
}
}
}
})
你可以在component中通過 this.props 取到所有的prop值。
當然,小程序不支持 props 的概念,所有的props都會合并到data中
component的methods
組件私有的方法,但最終會被合并到page的config屬性里,以便于在component的template中調用。
Page
wx-component 會重新定義小程序原有的 Page 方法,所以你只需要在項目根目錄的 app.js 中require一次就可以,后續無需重新require:
/project/app.js
require("/libs/wx-component/index")
App({
onLaunch() {
...
},
globalData: {
...
}
})
component的onLoad和onUnload
這兩個事件對應page的 onLoad 和 onUnload ,但不支持 onShow 等其他page事件,你可以在page的 onShow 中使用 this.childrens 獲取組件并調用其私有方法。
推薦的目錄結構
├─project 項目
├─components 功能組件
├─login 登錄組件
├─index.wxss
├─index.wxml
├─index.js
├─pages 頁面
component的結構
{
// 組件名
// 也可以不填,不填寫會用components/{X}/index.js
中的X命名
name: "login",
// 組件私有數據
data: {
item: [1, 2, 3]
},
// 組件屬性
// 可以預先定義默認值
// 也可以外部傳入覆蓋默認值
props: {
text: "start"
},
// 當組件被加載
onLoad() {
this.setData({
is_loaded: true
})
},
// 當組件被卸載
onUnload() {
this.setData({
is_unloaded: true
})
},
// 組件私有方法
methods: {
getMsg() {
...
},
sendMsg() {
...
}
},
// 其他
....
}</code></pre>
前面的路
由于這幾乎是以 Hack 的方式去解決非靜態微信組件化,data、props和methods的merge也會有些混亂,終究只是更方便更快速的解決業務需求。
期待微信小程序團隊盡快發布 Component 支持。
來自:https://juejin.im/post/58c7d2e40ce4630054836b90