如何使用小程式自定義元件功能
小程式開發時通過自定義元件將頻繁使用的模組抽取出來,簡化程式碼;

實現難點
小程式文件相關的說明太過於詳細,以至於不能快速上手使用,因此這裡從頑意小程式中拿出一個例子來說明如何使用小程式的自定義元件功能
知識準備
- 元件與頁面一樣由四個檔案組成,元件與頁面寫法相同,元件模板與元件資料結合後生成的節點樹,將被插入到元件的引用位置上,元件提供slot節點承載引用元件時提供的子節點;
程式碼實現
自定義元件
- 使用元件前需要在元件的json檔案中宣告,component欄位設定為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.父元件通過屬性將資料傳到子元件中,需要通過Component構造器的properties欄位定義,才能完成屬性名到屬性的對映; 2.子元件通過事件傳遞資料到父元件: - this.triggerEvent(' ',{},{}),第一個引數是自定義事件名稱,這個名稱是在頁面呼叫元件時bind的名稱,第二個物件傳遞需要的資料,第三個引數事件選項包括事件冒泡、捕獲等設定;
Component({ options: { addGlobalClass: true, //使用全域性的css樣式 }, /** * 元件的屬性列表 */ properties: { item: { type: Object, value: true, }, type: { type: String, value: true, }, orderid: { type: String, }, price: { type: Number, value: 0, } }, /** * 元件的初始資料 */ data: { showBtn: true, showTotalPrice: true }, /** * 元件的方法列表 */ methods: { cancleOrder: function (e) { var myEventDetail = { val: 'cancle' } ; this.triggerEvent('cancleOrder', myEventDetail) //cancleOrder是自定義名稱事件,父元件中使用 } } }) 複製程式碼