微信小程序-订单15min倒计时

336 阅读1分钟
  • 订单列表
 <view wx:for="{{list}}" wx:key="index">
      <van-divider />
      <view wx:if="{{item.orderStatus=='xxx'&&serviceFlag==0}}">
        支付倒计时
        <van-count-down data-orderId="{{item.orderId}}" bind:finish="finish" time="{{ item.countdown }}" />
      </view>
  </view>
import Toast from '@vant/weapp/toast/toast';
Page({
  data: {
    token: '',
    automaticType: '',//0,1
    page: 1,
    list: [],
    serviceFlag: null,
    loading: false,
    finished: false,
    active: 0,
    finishIds: [],
  },
  onShow() {
    if (this.data.token) {
      this.setData({
        page: 1,
        list: [],
        loading: false,
        finished: false,
      })
      if (this.data.active == 0) {
        this.data.active = 'xx'
      }
      this.getList()
    } else {
      this.setData({
        list: []
      })
    }
  },
  onLoad(options) {
    this.setData({
      serviceFlag: wx.getStorageSync('serviceFlag'),
    })
    if (options.active) {
      this.setData({
        active: 'xx'
      })
    }
    this.getInfo()
  },

  // 获取getInfo中automaticType 0,1:
  getInfo() {
    wx.http(
      '/getInfo'
    ).then(res => {
      this.setData({
        automaticType: res.user.automaticType
      })
    })
  },
  // 上拉下拉
  getList() {
    if (this.data.loading || this.data.finished) return
    this.setData({
      loading: true
    })
    wx.http('/list', {
      pageNum: this.data.page,
      pageSize: 10,
      orderStatus: this.data.active
    }).then(data => {
      this.setData({
        list: this.data.list.concat(data.rows || []),
        loading: false,
        finished: Boolean(data.total < 10)
      })
      // 初始化订单数据和倒计时
      const orders = this.data.list.map(order => {
        const countdown = this.calculateCountdown(order.createTime);
        return { ...order, countdown };
      });

      this.setData({ list: orders });
      wx.stopPullDownRefresh()
    })
  },
  calculateCountdown: function (createTime) {
    const create = new Date(createTime)
    // 假设倒计时时间为15分钟
    let countdownTime = new Date(create.getTime() + 15 * 60 * 1000);
    // 获取当前时间
    let now = new Date();

    // 计算时间差(毫秒)
    const diff = countdownTime - now;
    //多一秒
    return diff + 1 * 1000
  },
  finish(e) {
    let { orderId } = e.currentTarget.dataset
    let arr = this.data.finishIds;
    arr.push(orderId);
    this.setData({ finishIds: arr });
    let numbers = this.data.finishIds
    if (!numbers.includes(orderId)) {
      this.updateList()
    }
  },
  onPullDownRefresh() {
    if (this.data.token) {
      this.updateList()
    }
  },
  updateList() {
    this.setData({
      page: 1,
      list: [],
      loading: false,
      finished: false,
    })
    this.getList()
  },
  onReachBottom() {
    if (this.data.token) {
      this.setData({
        page: this.data.page + 1,
        loading: false
      })
      this.getList()
    }
  },
})