
簡單預(yù)覽
網(wǎng)上一直再埋怨小程序沒有組件化,現(xiàn)在小程序升級了,提供了自定義組件 Component,目前處于公測階段。今天體驗一回,將之前使用 template 寫的評分組件重寫了下。
小程序自定義評分組件 template(精度0.1)
從小程序基礎(chǔ)庫版本 1.6.3 開始,小程序支持簡潔的組件化編程。
自定義組件
自定義組件類似頁面,由 json wxml wxss js 4個文件組成。
-
rating.json
必需在 json 文件中聲明為組件{ "component": true } -
rating.wxml
wxml 文件中編寫布局<view class='com-rating'> <view class='rating-icon' wx:for='{{[1,2,3,4,5]}}' wx:key='*this' bindtap='_handleTap' data-num='{{item}}'> <view class='rating-on' style='width:{{rating >= (max/5)*item ? 1 : rating < (max/5)*(item-1) ? 0 : (rating*10)%(max/5*10)/(max/5*10)}}em'> <image src='./../../images/rating_on_icon.png' mode='widthFix' style='width:1em' /> </view> <view class='rating-off' style='width:1em;'> <image src='./../../images/rating_off_icon.png' mode='widthFix' style='width:1em' /> </view> </view> </view> -
rating.wxss
修飾組件樣式.com-rating { display: inline-block; letter-spacing: .3em; position: relative; } .com-rating .rating-icon, .com-rating .rating-on, .com-rating .rating-off { display: inline-block; } .com-rating .rating-icon:not(:last-child) { margin-right: .2em; } .com-rating .rating-on { color: black; position: absolute; overflow: hidden; padding: 0; margin: 0; } .com-rating .rating-off { color: #DBDBDB; padding: 0; margin: 0; } -
rating.js
初始化組件屬性及事件Component({ // 聲明組件屬性及默認值 properties: { rating: { type: Number, // 必需 指定屬性類型 [String, Number, Boolean, Object, Array, null(任意類型)] value: 10 }, max: { type: Number, value: 5 }, disabled: { type: Boolean, value: false } }, // 組件私有和公開的方法,組件所使用的方法需在此聲明 methods: { _handleTap: function (e) { if (this.data.disabled) return; const { max } = this.data; const { num } = e.currentTarget.dataset; this.setData({ rating: max / 5 * num }) // 自定義組件事件 this.triggerEvent('change', { value: max / 5 * num }, e); } } })
使用
組件除了在 page 中使用外,在組件中也可以使用。以 page 舉例。
-
.json
在 json 文件中需聲明組件{ "usingComponents": { "com-rating": "/components/rating/rating" } } -
.wxml
<!-- bindchange 事件需與組件中定義的自定義事件保持一致,如組件定義的 change,這里使用的是 bindchange --> <com-rating max="10" rating='6.5' bindchange='handleChange' /> -
.js
在 js 文件中監(jiān)聽事件/** *@param {Object} e 組件自定義事件傳遞的數(shù)據(jù) */ handleChange: function(e) { this.setData({ rating: e.detail.value }) }
組件樣式有限制,這里沒有使用 FontAwesome,如需使用字體圖標(biāo)可查看小程序自定義評分組件 template(精度0.1)
更多使用可以查看我開源的小程序

小程序
開源地址