自定義組件star-score:
star-score.js內容:
Component({
/**
* 組件的屬性列表
*/
properties: {
// 是否只讀
disabled: {
type: Boolean,
value: false
},
// 傳入的分值
val: {
type: Number,
value: 0
},
// 星星的寬度
starW: {
type: Number,
value: 40
},
// 星星的高度
starH: {
type: Number,
value: 40
}
},
/**
* 組件的初始數據
*/
data: {
stars: [0, 1, 2, 3, 4],
// 圖片路徑
starNo: '../../assets/star-no.png',
starHalf: '../../assets/star-half.png',
starFull: '../../assets/star-Full.png'
},
/**
* 組件的方法列表
*/
methods: {
// 選中半顆星
_selectHalf(e) {
let val = e.currentTarget.dataset.val
if (this.data.val == 0.5 && e.currentTarget.dataset.val == 0.5) {
// 只有半顆星的時候,再次點擊,變爲0顆
val = 0;
}
this.setData({
val: val
})
// 向父組件傳值
this.triggerEvent('_selectStar', this.data.val)
},
// 選中滿星
_selectFull(e) {
let val = e.currentTarget.dataset.val
this.setData({
val: val
})
// 向父組件傳值
this.triggerEvent('_selectStar', this.data.val)
}
}
})
star-score.wxml的內容:
<!-- 五星打分組件 -->
<view>
<block wx:for="{{stars}}" wx:key="{{index}}">
<image class="star-image"
style="width: {{starW}}rpx; height: {{starH}}rpx;"
src="{{val > item ? (val-item < 1 ? starHalf : starFull) : starNo}}">
<view class="item"
style="left: 0rpx; width: {{starW}}rpx; height: {{starH}}rpx;"
data-val="{{item+0.5}}"
bindtap="{{disabled ? '' : '_selectHalf'}}"></view>
<view class="item"
style="left: {{starW/2}}rpx; width: {{starW}}rpx; height: {{starH}}rpx;"
data-val="{{item+1}}"
bindtap="{{disabled ? '' : '_selectFull'}}"></view>
</image>
</block>
</view>
star-score.wxss的內容:
.star-image{
position: relative;
}
.item{
position: absolute;
top: 0;
}
調用自定義組件star-score:
// 可選配置disabled、 starW、 starH
<star-score val="{{3}}"></star-score>
星星素材圖
![圖片描述 圖片描述](http://static.javashuo.com/static/loading.gif)
![圖片描述 圖片描述](http://static.javashuo.com/static/loading.gif)
![圖片描述 圖片描述](http://static.javashuo.com/static/loading.gif)