返回
微信小程序九宫格抽奖组件
前端
2023-09-14 19:52:02
[开盖即食]微信小程序九宫格抽奖component组件分享
开盖即食
这次继续分享第二个抽奖组件,参考了网上多个版本,本人根据实际工作中进行了一些优化,并将其做成component组件方便大家食用~
1、现在上吃的,呸,上代码
页面引用部分:
<!-- 九宫格抽奖页面 -->
<view class="container">
<view class="grid" wx:for="{{grids}}" wx:key="index">
<block wx:if="{{item.type == 'title'}}">
<view class="title">{{item.text}}</view>
</block>
<block wx:if="{{item.type == 'blank'}}">
<view class="blank"></view>
</block>
<block wx:if="{{item.type == 'prize'}}">
<view class="prize" bindtap="handlePrize">{{item.text}}</view>
</block>
</view>
</view>
Component组件部分:
// 抽奖组件
Component({
properties: {
// 抽奖数据
data: {
type: Array,
value: []
},
// 抽奖结束后的回调函数
onFinish: {
type: Function,
value: null
}
},
data: {
// 当前抽奖索引
currentIndex: 0,
// 抽奖结果
result: null,
// 抽奖状态
status: 'ready' // ready, running, finished
},
methods: {
// 开始抽奖
start() {
if (this.data.status !== 'ready') {
return
}
this.setData({
status: 'running'
})
const interval = setInterval(() => {
// 随机生成下一个索引
const nextIndex = Math.floor(Math.random() * this.data.data.length)
this.setData({
currentIndex: nextIndex
})
}, 100)
// 1秒后停止抽奖
setTimeout(() => {
clearInterval(interval)
this.setData({
status: 'finished',
result: this.data.data[this.data.currentIndex]
})
// 执行结束回调函数
this.data.onFinish && this.data.onFinish(this.data.result)
}, 1000)
},
// 重新开始抽奖
reset() {
this.setData({
currentIndex: 0,
result: null,
status: 'ready'
})
}
}
})
2、食用说明
1、在需要使用抽奖组件的页面中,先引用component组件。
// 在page.json中引用component组件
{
"usingComponents": {
"lottery-grid": "/components/lottery-grid/lottery-grid"
}
}
2、在页面中使用抽奖组件。
<!-- 九宫格抽奖页面 -->
<view class="container">
<lottery-grid data="{{lotteryData}}" onFinish="handleFinish"></lottery-grid>
</view>
3、在页面中定义抽奖数据。
data: {
lotteryData: [
{
type: 'title',
text: '九宫格抽奖'
},
{
type: 'blank'
},
{
type: 'prize',
text: '一等奖'
},
{
type: 'blank'
},
{
type: 'prize',
text: '二等奖'
},
{
type: 'blank'
},
{
type: 'prize',
text: '三等奖'
},
{
type: 'blank'
},
{
type: 'prize',
text: '四等奖'
}
]
}
4、在页面中定义抽奖结束后的回调函数。
methods: {
handleFinish(result) {
console.log('抽奖结果:', result)
}
}
3、说一下
本次分享的微信小程序九宫格抽奖组件,可以帮助您快速集成九宫格抽奖功能。该组件基于Component组件开发,方便复用和维护。同时,为了方便大家食用,还提供代码页面引用和Component组件部分。如果您有九宫格抽奖的需求,不妨试一试这款组件。