Code前端首页关于Code前端联系我们

微信小程序开发:独特的倒计时组件

terry 2年前 (2023-09-23) 阅读数 61 #移动小程序
  • 最近沉迷于写小程序。我需要在我的业务中实现倒计时功能。考虑到扩展性和易用性,我把它放在一个组件中(习惯了还得写JSX)抱怨小程序自定义组件繁琐)
  • 这是新手第一次在掘金写点东西。比较简单的事情会拉低整篇掘金文章的水平(请简单点~)

需求

  • 是配置倒计时时间
  • 倒计时结束后执行事件
  • 时间可配置

步骤

  • 首先定义自定义组件的属性。这里,两个父组件被传递给它。倒计时组件参数 目标倒计时时间、格式倒计时时间格式
properties: {
    target: {
      type: String,
    },
    format: {
      type: Function,
      default: null
    }
},
复制代码
  • 组件的生命周期决定了生命周期函数。在微信小程序的自定义组件部分,是指在特殊时间或者特殊帧事件时自动激活的组件本身的某些功能。其中,最重要的生命周期包含组件的生命日期 created attached detached。您可以在官方文档中阅读有关微信各个组件的信息:定时事件initTime? wxml完整代码
<wxs  module="utils" />
<wxs  module="comm" />
<view class="count-down">
  <text wx:if="{{result!==''}}">{{result}}</text>
  <block wx:else>
    <text wx:if="{{comm.numberToFixed(d)>0}}">{{d}}天</text>
    <text>{{utils.fixedZero(h)}}</text>
    <text style="font-weight: 500">:</text>
    <text>{{utils.fixedZero(m)}}</text>
    <text style="font-weight: 500">:</text>
    <text>{{utils.fixedZero(s)}}</text>
  </block>
</view>
复制代码

引入了wxs文件中的两个函数
WXS(微信脚本)是一种小程序的脚本语言。与WXML结合,可以编辑页面的结构。官方文档

function fixedZero(val) {
  return val * 1 < 10 ? '0' + val : val;
}
//保留 pos位小数
function numberToFixed(number, pos) {
  if (number === null || number === '' || number < 0) return ''
  return parseFloat(number).toFixed(pos)
}
复制代码

零件使用

  • 介绍方法
"usingComponents": {
    "countDown": "../../../components/countDown/countDown"
  },
复制代码
  • 代码演示
 <countDown bind:onEnd="getPageList" format="{{formatTime}}" target="{{creatTargetTime}}" />
复制代码
const formatChinaDate = mss => {
  let days = parseInt(mss / (1000 * 60 * 60 * 24));
  let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
  let seconds = parseInt((mss % (1000 * 60)) / 1000);
  return days + ' 天 ' + hours + ' 小时 ' + minutes + ' 分钟 ' + seconds + ' 秒 ';
};
data:{
    formatTime:formatChinaDate,
    creatTargetTime:1556428889000, //时间戳
}

getPageList:function(){
    //倒计时结束啦
    console.log('倒计时结束啦')
}
复制代码

API

参数 ❀ry♷说明 默认值
格式 时间格式显示功能(时间)x 天 00:00:00
目标目标时间日期日期日期 日期日期
链接:https://juejin. im/post/5cc568dcf265da037b611ad4
来源:掘金
版权归作者所有。商业转载请联系作者获得许可。非商业转载请注明来源。

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门