微信小程序原生JS:优惠券列表(下单可用/失效/所有可用)

989 阅读6分钟

优惠券列表

优惠券三种状态
1:个人中心页面>优惠券<tab1所有可用优惠券:用于查看
2:个人中心页面>优惠券<tab2所有失效优惠券:用于查看
3:下单页选择优惠券跳转>符合当前类目下的可用及不可用优惠券:用于选择并使用

效果:

JS代码

const app = getApp();
import Serve from '../../../api/my.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false,
    loadEnd: false,
    isShowPicker: false,
    tabs: [{
      label: "可用优惠券",
      type: 0
    }, {
      label: "已失效优惠券",
      type: 2
    }],
    items: [],
    couponType: 0, // 0 个人中心可用优惠券 1 下单页可用优惠券 2 已失效优惠券
    type: '', // 优惠券品类 1上门寄件 2帮我取 3帮我买
    totalPrice: '', // 订单金额
    pageSize: 10, // 分页:每页10条
    pageNum: 1,	// 当前页数
    totalNum: 0, // 总张数
    noUse: false // 根据缓存判断是否选中优惠券
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.loadFontFace({ // 引入数字字体
      family: 'DIN-Bold',
      source: 'url("https://file.baimipay.cn/DIN-Bold.otf")',
      success: console.log
    })
    if (options.type && options.couponType) {
      this.setData({
        couponType: options.couponType,
        type: options.type,
        totalPrice: options.totalPrice
      })
    }
    this.load();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.load();

  },

  load() {
    this.onPullDownRefresh()
  },

  /**
   * 页面相关事件处理函数--监听用户上拉刷新
   */
  onPullDownRefresh: function() {
    // app.loadingTip()
    this.setData({
      pageNum: 1,
      items: []
    });
    this.getListData();
  },

  /**
   * 页面下拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (this.data.totalNum > this.data.items.length && this.data.totalNum > 0) {
      app.loadingTip()
      this.setData({
        pageNum: this.data.pageNum + 1,
      });
      this.getListData();
    }
  },

  // tab转换
  switchTab(e) {
    this.setData({
      couponType: e.currentTarget.dataset.type
    });
    this.onPullDownRefresh()
  },

  //点击使用规则
  toggle(e) {
    const that = this
    const index = e.currentTarget.dataset.index
    const items = this.data.items
    for (var i = 0; i < items.length; i++) {
      if (i != index) {
        items[i].show = false
      }
    }
    items[index].show = !items[index].show
    that.setData({
      items: items
    })
  },


  //获取会员列表
  getListData() {
    if (this.data.loading) {
      return false;
    }
    if (this.data.loadEnd) {
      return false;
    }
    wx.showLoading({
      title: '加载中...',
    })
    this.setData({
      loading: true
    })
    const items = this.data.items;
    let listData = [];
    let couponType = this.data.couponType;
    if (couponType != 2) {
      couponType = 0
    }
    const data = {
      status: couponType, //0可使用,1已使用,2已失效
      totalPrice: this.data.totalPrice, //订单金额
      type: this.data.type, //优惠券品类 1上门寄件 2帮我取 3帮我买
      curPage: this.data.pageNum,
      pageSize: this.data.pageSize,
    }
    Serve.getMyCouponList(data).then(res => {
      if (res.success) {
        res.d.list.forEach(item => {
          item.show = false,
            item.useStartTime = new Date(item.useStartTime * 1000).format('yyyy-MM-dd'),
            item.useEndTime = new Date(item.useEndTime * 1000).format('yyyy-MM-dd')
        })
        if (data.type != '') {
          res.d.list.forEach(item => {
            item.syncPick = false
          })
        }
        if (wx.getStorageSync('is_Pick')) {
          if (wx.getStorageSync('is_Pick').id == 0) {
            this.setData({
              noUse: true
            })
          } else {
            for (let i in res.d.list) {
              if (res.d.list[i].id == wx.getStorageSync('is_Pick').id) {
                res.d.list[i].syncPick = true
              }
            }
          }

        }

        if (this.data.pageNum > 1) {
          listData = items.concat(res.d.list)
        } else(
          listData = res.d.list
        )
        this.setData({
          loaded: true,
          loading: false,
          items: listData,
          totalNum: res.d.totalNum
        })
        if (couponType == 0 && res.d.totalNum != 0) {
          this.setData({
            [`tabs[0].label`]: '可用优惠券 · ' + res.d.totalNum,
            [`tabs[1].label`]: '失效优惠券'
          })
        } else if (couponType == 2 && res.d.totalNum != 0) {
          this.setData({
            [`tabs[0].label`]: '可用优惠券 ',
            [`tabs[1].label`]: '失效优惠券 · ' + res.d.totalNum,
          })
        }

      }
      console.log(this.data.items)
      wx.hideLoading()
    }).catch(res => {
      wx.hideLoading()
      app.commonTip(res)
    })

  },

  //点击优惠券
  chooseCoupon(e) {
    wx.setStorageSync('counte', 1)
    var items = this.data.items
    
    var id = e.currentTarget.dataset.id
    var couponId = e.currentTarget.dataset.couponid
    
    console.log(e.currentTarget.dataset)
    if (e.currentTarget.dataset.index != undefined) {
      var index = e.currentTarget.dataset.index
    }
    for (let i in items) {
      items[i].syncPick = false
    }
    if (id != 0) {
      items[index].syncPick = true
    }

    this.setData({
      items: items
    })
    const date = {
      id: id
    }
    wx.setStorageSync('is_Pick', date)
    const data = {
      couponId: couponId,
      totalPrice: this.data.totalPrice
      
    }
    const pages = getCurrentPages(); //获取当前页面js里面的pages里的所有信息。
    const prevPage = pages[pages.length - 2]; //上一个页面
    if(id!=0){
      Serve.couponAmount(data).then(res => {
        if (res.success){
          prevPage.setData({
            activeId: id,
            isShowLayer: false,
            amout: res.d.couponMoney,
            noUse: false
          })
        }
      }).catch(err => {
        console.error(err);
      })
    }else {
      prevPage.setData({
        noUse: true,
        activeId: id,
        isShowLayer: false,
        amout: '0'
      })
    }
    wx.navigateBack({
      delta: 1
    })
  },

})

WXML代码

<view class='page {{couponType==1?"":"bgColor"}}'>
  <!-- tab栏转换 -->
  <view class='nouse' wx:if='{{couponType==1}}' bindtap="chooseCoupon" data-id='0' data-couponId='0'>
    <text>不使用优惠券</text>
    <image src='{{noUse?"https://file.baimipay.cn/xuanze2x.png":"https://file.baimipay.cn/weixuan2x.png"}}'></image>
  </view>
  <view class='header' wx:else>
    <view class='title'>
      <view class='col-pre title-tab {{couponType==item.type?"tab-active":""}}' wx:for="{{tabs}}" wx:key="index" data-type="{{item.type}}" bindtap='switchTab'>{{item.label}}
        <view class='{{couponType==item.type?"col-active":""}}'></view>
      </view>
    </view>
  </view>
  <view class='list' wx:if='{{items.length!=0}}' style='{{couponType==1?"padding-top:0rpx;":""}}'>
    <view wx:for='{{items}}' wx:key="{{item.id}}" style='margin-top:20rpx;'>
      <view class='couponbg'>
        <view class='coupon-price'>
          <image wx:if='{{item.couponType==1}}' src='{{couponType!=2?"https://file.baimipay.cn/jijian@2x.png":"https://file.baimipay.cn/jijian22x.png"}}'></image>
          <image wx:elif='{{item.couponType==2}}' src='{{couponType!=2?"https://file.baimipay.cn/qusong@2x.png":"https://file.baimipay.cn/qusong22x.png"}}'></image>
          <image wx:elif='{{item.couponType==3}}' src='{{couponType!=2?"https://file.baimipay.cn/mai@2x.png":"https://file.baimipay.cn/mai22x.png"}}'></image>
          <view wx:if='{{item.rulesType!=3}}' style='{{couponType!=2?"":"color:#ccc;"}}'><text style='font-size: 60rpx;'>{{we.toFixed(item.maxAmout)}}</text>.{{we.toFixed2(item.maxAmout)}}</view>
          <view wx:elif='{{item.rulesType==3}}' style='{{couponType!=2?"":"color:#ccc;"}}'>
            <text style='font-size: 60rpx;'>{{we.toFixed(item.discount)}}</text>.{{we.toFixed2(item.discount)}}
            <view class='zhe' style='{{couponType!=2?"":"color:#ccc;"}}'></view>
          </view>
        </view>
        <view class='coupon-title' bindtap="{{item.availability==1&&couponType==1?'chooseCoupon':''}}" data-couponid='{{item.couponId}}' data-id='{{item.id}}' data-index='{{index}}'>
          <view class='title' style='{{couponType!=2?"":"color:#ccc;"}}'>{{item.couponName}}</view>
          <view class='date' style='{{couponType!=2?"":"color:#ccc;"}}'>有效期:{{we.toDate(item.useStartTime)}} - {{we.toDate(item.useEndTime)}}</view>
          <image class='choose' wx:if="{{item.syncPick==false&&couponType==1}}" src="https://file.baimipay.cn/{{item.availability==0?'Invalidchose@2x':'weixuan2x'}}.png"></image>
          <image class='choose' wx:elif="{{item.syncPick&&couponType==1}}" src="https://file.baimipay.cn/xuanze2x.png"></image>
        </view>
      </view>
      <view class='content' bindtap="toggle" data-index='{{index}}'>
        <view style='{{couponType!=2?"width:92%;":"color:#ccc;width:92%;"}}' class='{{item.show?"":"shouqi ellipsis"}}'>
          <rich-text nodes="{{item.couponRule}}"></rich-text>
        </view>
        <icon class='iconfont {{item.show?"iconzhankai":"iconshouqi"}} icon'></icon>
      </view>
    </view>
  </view>

  <view class='message' wx:if="{{(items.length==0&&couponType==0)||(items.length==0&&couponType==2)||(items.length==0&&couponType==1)}}">
    <image src='https://file.baimipay.cn/dingdan%20kong2x.png' mode='aspectFit' class="img1"></image>
    <view class='text' wx:if='{{couponType==0||couponType==1}}'>暂无可用优惠券</view>
    <view class='text' wx:elif='{{couponType==2}}'>无失效优惠券</view>
  </view>


</view>

<!-- js过滤器 -->
<wxs module="we">
  var toDate = function(value) {
    while (value.indexOf('-') >= 0)
      value = value.replace('-', '.');
    if (value) {
      return value
    }
  }
  var toFixed = function(value) {
    if (value) {
      return parseFloat(value / 100).toFixed(2).split('.')[0]
    } else {
      return value
    }
  }
  var toFixed2 = function(value) {
    if (value) {
      return parseFloat(value / 100).toFixed(2).split('.')[1]

    } else {
      return value
    }

  }
  module.exports = {
    toDate: toDate,
    toFixed: toFixed,
    toFixed2: toFixed2
  }
</wxs>

WXSS代码

/* pages/myInfo/myCoupon/use/index.wxss */

page {
  background-color: #fff;
}

.nouse {
  height: 100rpx;
  background-color: #fff;
  border: 2rpx solid #f3cb3c;
  border-radius: 20rpx;
  margin: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.nouse text {
  margin-left: 20rpx;
  color: #333;
  font-size: 32rpx;
}

.nouse image {
  width: 44rpx;
  height: 44rpx;
  margin-right: 20rpx;
}

.bgColor {
padding-top: 90rpx;
background-color: #f6f6f6;
}

.header {
  background: #fff;
  border-top: 1rpx solid #e8e9ea;
  position: fixed;
  width: 100vw;
  z-index: 9;
  left: 0;
  top: 0;
  box-shadow: 0rpx 0rpx 10rpx #eee;
}

.title {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.title-tab {
  height: 100rpx;
  line-height: 100rpx;
  color: #666;
  font-size: 30rpx;
  width: 50%;
  text-align: center;
}

.tab-active {
  color: #333;
  font-weight: 600;
}

.swicth-tab {
  width: 100%;
  display: flex;
  padding: 24rpx 0;
  box-sizing: border-box;
  border-top: 1rpx solid #e8e9ea;
  border-bottom: 1rpx solid #e8e9ea;
}

.swicht-tab_item {
  display: flex;
  width: 50%;
  justify-content: center;
  align-items: center;
}

.swicth-tab .swich-tab_icon {
  width: 24px;
  height: 20px;
  margin-left: 10rpx;
}

.swicth-tab image {
  max-width: 100%;
  max-height: 100%;
}

.list {
  padding: 20rpx;
  background-color: #fff;
}

.list .couponbg {
  width: 100%;
  height: 160rpx;
  background-image: url("https://file.baimipay.cn/kuang@2x.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  display: flex;
  justify-content: space-between;
  /* display: inline-block;
  align-items: center; */
}

.icon {
  font-size: 14rpx;
  color: #cdcdcd;
  position: absolute;
  width: 8%;
  right: 0%;
  top: -3%;
}

.coupon-price {

  width: 200rpx;
  border-right: 2rpx dashed #f3cb3c;
}

.coupon-price image {
  width: 117rpx;
  height: 28rpx;
  margin: 8rpx 12rpx;
}

.coupon-price view {
  font-family: 'DIN-Bold';
  color: #333;
  font-size: 30rpx;
  text-align: center;
  width: 100%;
  position: relative;

}

.coupon-title {
  padding: 23rpx 20rpx;
  position: relative;
}

.coupon-title .title {
  width: 460rpx;
  height: 80rpx;
  color: #333;
  font-size: 32rpx;
}

.coupon-title .date {
  width: 460rpx;
  color: #999;
  font-size: 24rpx;
}

.content {
  border: 2rpx solid #f3cb3c;
  border-radius: 0 0 30rpx 30rpx;
  background-color: #fff;
  padding: 15rpx 23rpx;
  border-top: none;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}

.shouqi {
  height: 38rpx;
  overflow: hidden;
}

.message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -70%);
  color: #999;
  text-align: center;
}

.message .img1 {
  width: 398rpx;
  height: 288rpx;
}

.message .text {
  margin-top: 41rpx;
}

.choose {
  width: 22px;
  height: 22px;
  position: absolute;
  right: 5%;
  top: 60%;
}

.zhe{
  font-size: 20rpx !important;
  position: absolute !important;
  left: 30%;
  display: inline-block;
  top: 0%;
}