微信小程序> 小程序倒计时自定义组件

小程序倒计时自定义组件

浏览量:1406 时间: 来源:lzh5997

所有的事件,都是在组件里面完成,父组件,只需要把需要的值传递过来,就可以调用

组件的js文件// components/countDown/countDown.jsComponent({// 目前组件,只接受时间戳,其他的没有做// 现在的时间,和结束时间,都必须从后台获取,因为客户端时间不一致  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  }})

版权声明

即速应用倡导尊重与保护知识产权。如发现本站文章存在版权问题,烦请提供版权疑问、身份证明、版权证明、联系方式等发邮件至197452366@qq.com ,我们将及时处理。本站文章仅作分享交流用途,作者观点不等同于即速应用观点。用户与作者的任何交易与本站无关,请知悉。

产品经理

手机 : 13312967497

擅长 : 小程序流量变现

扫码领取礼包

最新资讯

热门模板

  • 头条
  • 搜狐
  • 微博
  • 百家
  • 一点资讯
  • 知乎