標簽: 小程序 component
需求
小程序開發(fā)時通過自定義組件將頻繁使用的模塊抽取出來,簡化代碼;
實現(xiàn)訂單頁面的一個小組件模塊
實現(xiàn)難點
小程序文檔相關(guān)的說明太過于詳細晋辆,以至于不能快速上手使用,因此這里從頑意小程序中拿出一個例子來說明如何使用小程序的自定義組件功能
知識準備
- 組件與頁面一樣由四個文件組成,組件與頁面寫法相同按脚,組件模板與組件數(shù)據(jù)結(jié)合后生成的節(jié)點樹,將被插入到組件的引用位置上敦冬,組件提供slot節(jié)點承載引用組件時提供的子節(jié)點辅搬;
代碼實現(xiàn)
自定義組件
- 使用組件前需要在組件的json文件中聲明,component字段設(shè)置為true
{
"component": true,
"usingComponents": {}
}
2.wxml中編寫組件模板脖旱,wxss加入樣式
<wxs module="filters" src="../../utils/numberic.wxs"/>
<view class="orderCard" >
<view class='commodity flex-box ai-s'>
<image class='commodityImg' src="{{item.image}}"></image>
<view class='content flex-1'>
<view class='commodityName'>{{item.name}}</view>
<view class='commoditySpecification'>{{item.standardName}}</view>
<view class='commoditySpecification'>{{item.standardName}}</view>
</view>
<view class='price'>¥ {{ item.price }}</view>
</view>
<view class='money flex-box jc-e' wx:if="{{showTotalPrice}}">
<view class='amount'>共{{item.num}}件商品</view>
<view class='allPay'>
實付:
<text class='allPayMoney'>¥ {{ price }}</text>
</view>
</view>
<view class='btnBox flex-box jc-e ai-ce' wx:if="{{showBtn}}">
<view class='btn seeMove' wx:if="{{type === 'DELIVER' || type === 'RECEIVE'}}">查看物流</view>
<view
class='btn return'
wx:if="{{type === 'CREATE'}}"
style="color:'#ff3366'"
data-id="{{orderid}}"
catchtap="cancleOrder"
>
取消訂單
</view>
</view>
</view>
頁面引用組件
1.在頁面的json文件中配置引入的組件
{
"usingComponents": {
"orderCard": "../../base/orderCard/orderCard"
}
}
2.頁面中使用自定義組件
<view class='orderCardBox' wx:for="{{totalData}}" wx:key="{{item.orderId}}" >
<orderCard
bindtap="switchToOrderDetail"
item="{{item.shoppingCartPageWebVO}}"
type="{{item.orderType}}"
orderid="{{item.orderId}}"
data-orderid="{{item.orderId}}"
price="{{item.price}}"
bind:cancleOrder="refreshPage"
>
</orderCard>
</view>
父組件與子組件的通信
1.父組件通過屬性將數(shù)據(jù)傳到子組件中堪遂,需要通過Component構(gòu)造器的properties字段定義,才能完成屬性名到屬性的映射萌庆;
2.子組件通過事件傳遞數(shù)據(jù)到父組件:
- this.triggerEvent(' ',{},{}),第一個參數(shù)是自定義事件名稱溶褪,這個名稱是在頁面調(diào)用組件時bind的名稱,第二個對象傳遞需要的數(shù)據(jù)践险,第三個參數(shù)事件選項包括事件冒泡猿妈、捕獲等設(shè)置;
Component({
options: {
addGlobalClass: true, //使用全局的css樣式
},
/**
* 組件的屬性列表
*/
properties: {
item: {
type: Object,
value: true,
},
type: {
type: String,
value: true,
},
orderid: {
type: String,
},
price: {
type: Number,
value: 0,
}
},
/**
* 組件的初始數(shù)據(jù)
*/
data: {
showBtn: true,
showTotalPrice: true
},
/**
* 組件的方法列表
*/
methods: {
cancleOrder: function (e) {
var myEventDetail = {
val: 'cancle'
} ;
this.triggerEvent('cancleOrder', myEventDetail)
//cancleOrder是自定義名稱事件巍虫,父組件中使用
}
}
})
參考文檔
往期精彩回顧
- Ant Design 組件 —— Form表單(一)
- Ant Design 組件 —— Form表單(二)
- CMS管理后臺入門指南 (Ant Design Pro v2.0)
- 實現(xiàn)點擊下載文件的幾種方法
- 在https中引入http資源所導(dǎo)致的問題
廣州蘆葦科技web前端