所有的事件,都是在組件裏面完成,父組件,只需要把需要的值傳遞過來,就可以調用
組件的js文件
// components/countDown/countDown.js
Component({
// 目前組件,只接受時間戳,其他的沒有做
// 現在的時間,和結束時間,都必須從後臺獲取,因爲客戶端時間不一致
properties: {
nowTime: {
type: Number
},
overTime: {
type: Number
}
},
data: {
time: null,
timer: null,
content: '',
flag: true,
text: ['天', '時', '分', '秒']
},
ready() {
this.time()
},
detached() {
// 頁面被被銷燬的時候,清除定時器
clearInterval(this.data.timer)
},
methods: {
time() {
this.setData({
timer: setInterval(() => {
this.countDown()
let time = this.data.time
time = time - 1
this.setData({
time: time
})
}, 1000)
})
},
countDown() {
// 解構賦值
let {
overTime,
nowTime,
timer
} = this.data
let time
if (overTime < nowTime) {
clearInterval(timer)
this.setData({
flag: false
})
return true
} else {
// 只有在第一次賦值
if (!this.data.time) {
let temporary = overTime - nowTime
this.setData({
time: temporary
})
}
time = this.data.time
if (time === 0) {
clearInterval(timer)
this.setData({
flag: false
})
return true
}
let day, hour, minute, second, content = '';
// 計算、天、時、分、秒
day = Math.floor(time / (60 * 60 * 24))
hour = Math.floor((time % (60 * 60 * 24)) / (60 * 60))
minute = Math.floor(((time % (60 * 60 * 24)) % (60 * 60)) / 60)
second = Math.floor(((time % (60 * 60 * 24)) % (60 * 60)) % 60)
let array = [day, hour, minute, second]
// 處理數據,如果、天、時、分、秒小於10,則拼接成09這種形式
let timeList = array.map((item, index) => item < 10 ? `0${item}` : item)
// 輸出,進行字符拼接
timeList.forEach((item, index) => {
content += `${item}${this.data.text[index]}`
})
this.setData({
content: content
})
}
}
}
})
wxml文件
<view wx:if="{{flag}}">{{content}}</view>
父組件
json配置文件
{
"usingComponents": {
"count": "/components/countDown/countDown"
}
}
wxml文件
<count now-time="{{nowTime}}" over-time="{{overTime}}"/>
js文件
Page({
data: {
nowTime: 1539089166,
overTime: 1539172160
}
})