1、新建文件夹 count-down,选中文件夹 ->右键->选择新建Component,会自动生成 4 个文件,即
- count-down.js
- count-down.json
- count-down.wxml 页面文件
- count-down.wxss 样式文件
2、编写倒计时组件代码
count-down.wxml
<text>{{time}}</text>
count-down.js
Component({
/**
* 组件的属性列表
*/
properties: {
target: Number, // 结束时间
callback: String, // 回调
clearTimer: Boolean // 清除定时器
},
/**
* 组件的初始数据
*/
data: {
time: ''
},
ready() {
this.getFinalTime();
},
/**
* 组件的方法列表
*/
methods: {
init() {
const self = this;
setTimeout(() => {
self.getFinalTime.call(self);
}, 1000);
},
getFinalTime() {
const data = this.data;
const gapTime = Math.ceil((data.target - new Date().getTime())/1000); // 距离结束时间
let time = '00:00:00';
if(gapTime > 0) {
let lastTime = gapTime % 86400;
const hour = this.formatNum(parseInt(lastTime/3600));
lastTime = lastTime % 3600;
const minute = this.formatNum(parseInt(lastTime/60));
const second = this.formatNum(lastTime% 60);
time = `${hour}:${minute}:${second}`;
if(!data.clearTimer) this.init.call(this);
}else {
this.endFn();
}
this.setData({
time: time
});
},
formatNum(num) {
return num > 9 ? num : `0${num}`;
},
endFn() {
this.triggerEvent('callback',{});
}
}
})
3、使用倒计时组件
index.json:在需要用的组件的json文件中引入倒计时组件
{
"usingComponents": {
"count-down": "../components/count-down/count-down"
}
}
index.wxml:页面显示
<view>倒计时</view>
<count-down
target="{{targetTime}}"
bindcallback="countDownCallbackFn"
clear-timer="{{clearTimer}}"
></count-down>
index.js:设置倒计时的参数
Page({
/**
* 页面的初始数据
*/
data: {
// 倒计时
targetTime: 0,
clearTimer: false
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({
targetTime: new Date().getTime() + 10*60000
});
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
this.setData({
clearTimer: true
});
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
/**
* 定时器回调
*/
countDownCallbackFn () {
console.log("结束回调")
}
})