微信小程序(十一)在wxml中使用自定義函數

背景:我們有時候需要在wxml中使用一些運算,包括但不限於四則運算、三目運算等,我們如果想要使用自定義的一些方法,就需要使用wxs來實現了,下面代碼簡單介紹了列表中倒計時的實現方法,以及使用wxs把時間戳轉換爲年月日時分秒的方法。詳見代碼:

目前小程序增加了直播功能,爲了在直播列表中加上開播倒計時提醒,我在wxml中簡單使用了wxs實現,具體代碼如下:

wxml代碼如下:

<wxs module="fn">
    module.exports = {
        formatterTimer: function (nowTime, compareTime) {
            var result = {};
            var nowTime = getDate().getTime();// 當前時間的時間戳 也就是系統時間戳
            var futureTime = compareTime * 1000;// 比較時間的時間戳
            // console.log("nowTime=="+nowTime);
            // console.log("compareTime=="+compareTime);
            // 未來的時間減去現在的時間 ;
            var resTime = (futureTime - nowTime) / 1000;
            // console.log("resTime=="+resTime);
            // 結束時間
            var zero = futureTime - nowTime;
            if (zero >= 0) { // 認爲還沒有到達結束的時間
                result.d_d = (Math.floor(resTime / 86400)) < 10 ? '0' + (Math.floor(resTime / 86400)) : (Math.floor(resTime / 86400));
                result.h_h = (Math.floor(resTime / 3600) % 24) < 10 ? '0' + (Math.floor(resTime / 3600) % 24) : (Math.floor(resTime / 3600) % 24);
                result.m_m = (Math.floor(resTime / 60) % 60) < 10 ? '0' + (Math.floor(resTime / 60) % 60) : (Math.floor(resTime / 60) % 60);
                result.s_s = (resTime % 60) < 10 ? '0' + (resTime % 60) : (resTime % 60);
                result.status = true;
            } else {
                result.d_d = '00';
                result.h_h = '00';
                result.m_m = '00';
                result.s_s = '00';
                result.status = false;
            }
            // console.log(JSON.stringify(result));
            return result.d_d+"天"+result.h_h+"小時"+result.m_m+"分鐘";
        }

}
  </wxs>
<view class="main">
    <block wx:for="{{roomData}}" wx:key="{{index}}">
        <navigator class="live-play-item clearfix" url="plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id={{item.roomid}}">
            <view class="live-play-status">
                <text wx:if="{{item.live_status==101}}" class="live-play-text playing">直播中</text>
                <text wx:elif="{{item.live_status==105}}" class="live-play-text playpause">暫停中</text>
                <text wx:elif="{{item.live_status==102}}" class="live-play-text playyu">未開始</text>
                <text wx:elif="{{item.live_status==103}}" class="live-play-text playend">已結束</text>
            </view>
            <view class="img-box">
                <image class="cover-img" mode="widthFix" src="{{item.anchor_img}}"></image>
            </view>
            <view class="title-box">
                <view wx:if="{{item.live_status==102}}" class="live-player-time">
                    距離開播:{{fn.formatterTimer(nowTime,item.end_time)}}
                </view>
                <view class="live-play-title">
                    {{item.name}}
                </view>
            </view>
        </navigator>
    </block>
    <view class="tips" wx:if="{{!hidden}}">~我是有底線的~</view>
</view>

wxss代碼如下:

.main{
  padding:26rpx;
  background:#f5f5f5;
}
.clearfix::after{
  display:block;
  height:0;
  clear:both;
  content:'';
}
.live-play-item{
  box-sizing: border-box;
  display: block;
  overflow: hidden;
  position:relative;
  /* border:1rpx solid red; */
  margin-bottom:40rpx;
  border-radius:16rpx;
}
.live-play-status{
  position:absolute;
  right:20rpx;
  top:18rpx;
}
.live-play-text{
  display:block;
  font-size:26rpx;
  position:relative;
}
.playing{
  color:#228b22;
}
.playpause{
  color:#d2691e;
}
.playyu{
  color:#ff0000;
}
.playend{
  color:#708090;
}
.live-play-text::before{
  display:inline-block;
  content:'';
  width:10rpx;
  height:10rpx;
  border-radius:100%;
  position:absolute;
  top:18rpx;
  left:-20rpx;
}
.playing::before{
  background:#228b22;
}
.playpause::before{
  background:#d2691e;
}
.playyu::before{
  background:#ff0000;
}
.playend::before{
  background:#708090;
}
.img-box{
  /* box-sizing:border-box; */
  /* width:336rpx; */
}
.cover-img{
  display:block;
  width:698rpx;
  /* height:336rpx; */
}
.title-box{
  box-sizing:border-box;
  text-align:left;
  padding:24rpx 20rpx;
  background:#ffffff;
}
.live-play-title{
  font-family: PingFangSC-Regular;
  font-size: 32rpx;
  color: #231815;
  letter-spacing: 0;
  display:-webkit-box;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  -webkit-box-orient:vertical;
  -webkit-line-clamp:1;
  line-height:32rpx;
}
.live-player-time{
  font-family: PingFangSC-Regular;
  font-size: 28rpx;
  color: #231815;
  letter-spacing: 0;
  padding-bottom:16rpx;
}
.tips{
  text-align: center;
  font-size:26rpx;
  color:#333333;
}

js代碼如下:

import util from '../../utils/util.js';
//獲取應用實例
const app = getApp()
var page;//當前頁
var start;//當前條
var limit = 10;//每頁多少條
Page({
  /**
   * 頁面的初始數據
   */
  data: {
    livePlayData:'',//直播數據
    roomData:'',//直播間數據
    total:'',//總數據
    hidden:true,
  },
  /**
   * 生命週期函數--監聽頁面加載
   */
  onLoad: function (options) {
    var that = this;
    page = 0;
    start = 0;
    /**
    * 調取直播數據
    */
   util.requestData('Live/liveroomlist', {
    start:0,
    limit:limit
    }, (res) => {
      if (res.data.errcode == '0') {
        var data = res.data;
        that.setData({
          livePlayData:data,
          roomData:data.room_info,
          total:data.total
        })
      } else {
        console.log(1);
      }
    }, (res) => {
      // 錯誤信息提示
      console.log(res);
    })
  },
  /**
   * 生命週期函數--監聽頁面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命週期函數--監聽頁面顯示
   */
  onShow: function () {
    
  },

  /**
   * 生命週期函數--監聽頁面隱藏
   */
  onHide: function () {

  },

  /**
   * 生命週期函數--監聽頁面卸載
   */
  onUnload: function () {

  },

  /**
   * 頁面相關事件處理函數--監聽用戶下拉動作
   */
  onPullDownRefresh: function () {
    //做些什麼...
    // 顯示頂部刷新圖標
    wx.showNavigationBarLoading();
    var that = this;
    /**
    * 調取直播數據
    */
   util.requestData('Live/liveroomlist', {
    start:0,
    limit:limit
    }, (res) => {
      // 隱藏導航欄加載框
      wx.hideNavigationBarLoading();
      // 停止下拉動作
      wx.stopPullDownRefresh();
      if (res.data.errcode == '0') {
        var data = res.data;
        that.setData({
          livePlayData:data,
          roomData:data.room_info,
          total:data.total,
          hidden:true
        })
      } else {
        console.log(1);
      }
    }, (res) => {
      // 錯誤信息提示
      console.log(res);
    })
    page = 0;
    start = 0;
    wx.stopPullDownRefresh()//得到結果後關掉刷新動畫
  },

  /**
   * 頁面上拉觸底事件的處理函數
   */
  onReachBottom: function () {
    console.log("下拉加載更多數據");
    var that = this;
    // 頁數+1
    page = page + 1;
    start = page * limit;
    if(page*limit>=that.data.total){
      that.setData({
        hidden:false
      })
    }else{
       // 顯示加載圖標
       wx.showLoading({
        title: '玩命加載中',
      })
      /**
      * 調取下一頁直播數據
      */
      util.requestData('Live/liveroomlist', {
        start:start,
        limit:limit
        }, (res) => {
          if (res.data.errcode == '0') {
            var data = res.data;
            var newRoomData = data.room_info;
            const oldData = that.data.roomData;
            that.setData({
              livePlayData:data,
              roomData:oldData.concat(newRoomData),
              total:data.total
            })
            // 隱藏加載框
            wx.hideLoading();
          } else {
            console.log("error");
            // 隱藏加載框
            wx.hideLoading();
          }
        }, (res) => {
          // 錯誤信息提示
          console.log(res);
        })

    }
  },

  /**
   * 用戶點擊右上角分享
   */
  onShareAppMessage: function () {

  }
})

簡單效果圖如下:

以上完成wxs實現列表倒計時的需求,下面代碼在wxml中通過wxs實現時間戳轉爲時間的方法,代碼如下:

<wxs module="fn">
    var change = function(value) {
  value = value.replace(".000+0000","Z");
     var time = getDate(value);
    var year = time.getFullYear();
    var month = time.getMonth() + 1;
    var date = time.getDate();
    var hour = time.getHours();
    var minute = time.getMinutes();
    var second = time.getSeconds();
    month = month < 10 ? "0" + month : month;
    date = date < 10 ? "0" + date : date;
    hour = hour < 10 ? "0" + hour : hour;
    minute = minute < 10 ? "0" + minute : minute;
    second = second < 10 ? "0" + second : second;
    return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    }
    module.exports.change = change
</wxs>
<view>{fn.change(time)}}</view>

 data: {
    // time:"2017-12-28T10:43:49Z"
    time:"2019-07-23T13:46:51.000+0000"
  },

希望以上對大家有所幫助,或者哪位大神有更好的方法歡迎分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章