首页 > 编程语言 >微信小程序 自定义时间组件

微信小程序 自定义时间组件

时间:2022-08-22 14:57:29浏览次数:44  
标签:const 自定义 color 微信 date 组件 last font data

效果图

效果

代码

xml

<view class="date_bg_view">
</view>
<view class="date_content">
  <view class="date_title">
    <van-icon name="cross" class="close" size="20px" color="#999999" bindtap="onClose"/>
    <text class="date_title_txt">选择时间</text>
  </view>
  <view class="line"></view>
  <!-- 快速选择 -->
  <view class="date_quick_choose">
    <text class="date_quick_txt">快速选择</text>
    <view class="date_quick_show">
      <view class="quick_cell_flag" wx:for="{{dateList}}" wx:key="id" bindtap="handleQuickChoose" data-item="{{item}}" wx:if="{{item.flag}}">
        {{item.value}}
      </view>
      <view class="quick_cell" wx:for="{{dateList}}" wx:key="id" bindtap="handleQuickChoose" data-item="{{item}}" wx:if="{{!item.flag}}">
        {{item.value}}
      </view>
    </view>
  </view>
  <!-- 自定义时间 -->
  <view class="date_quick_choose">
    <text class="date_quick_txt">自定义时间</text>
    <view class="date_picker">
      <picker mode="date" value="{{startDate}}" start="2015-09-01" end="2999-12-31" bindchange="bindDateChange" data-type="1"  mask-style=" color='#0A3E79'">
        <view class="picker">
        {{startDate?startDate:'开始时间'}}
        </view>
      </picker> 
      <text style="width: 20rpx;height: 1rpx;background-color: #999999;"></text>
      <picker mode="date" value="{{endDate}}" start="2015-09-01" end="2999-12-31" bindchange="bindDateChange"  data-type="2">
        <view class="picker">
          {{endDate?endDate:'结束时间'}}
        </view>
      </picker>
    </view>
  </view>
  <button class="sure_btn" bindtap="handleSure"> 确定 </button>
</view>

wxss

.date_bg_view{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000000;
  opacity: 0.3;
  z-index: 10;
}
.date_content{
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  background-color: #ffffff;
  height: 65%;
  bottom: 0;
  position: fixed;
  left: 0;
  width: 100%;
  z-index: 11;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
}
.date_title{
  z-index: 11;
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 90rpx;
}
.close{
  width: 10%;
  margin: 10rpx;
}
.date_title_txt{
  margin-left: 30%;
  align-self: center;
  font-size: 35rpx;
  font-weight: bold;
  font-family: SourceHanSansCN-Medium;
}
.line{
  width: 100%;
  margin: 10rpx;
  height: 1rpx;
  background-color: #EEEEEE;
}
.date_quick_choose{
  z-index: 11;
  width: 100%;
  padding: 20rpx;
}
.date_quick_txt{
  font-family: SourceHanSansCN-Medium;
  margin: 20rpx;
  font-size: 30rpx;
  color: #666666;
  z-index: 12;
}
.date_quick_show{
  width: 100%;
  flex-wrap: wrap;
  display: flex;
  justify-content: flex-start;
  flex-direction: row;
  align-items: center;
  z-index: 12;
}
.quick_cell{
  padding: 5rpx;
  width: 29%;
  margin: 2%;
  font-size: 30rpx;
  text-align: center;
  z-index: 12;
  height: 60rpx;
  background-color: #F7F7F7;
  color: #999999;
  border-radius: 10rpx;
  font-family: SourceHanSansCN-Medium;
  border: 1rpx solid #999999;
}
.quick_cell_flag{
  padding: 5rpx;
  width: 29%;
  margin: 2%;
  font-size: 30rpx;
  text-align: center;
  z-index: 12;
  height: 60rpx;
  background-color: #FFFFFF;
  color: #0A3E79;
  border-radius: 10rpx;
  font-family: SourceHanSansCN-Medium;
  border: 1rpx solid #0A3E79;
}
.date_picker{
  display: flex;
  width: 80%;
  margin-left: 10%;
  justify-content: space-between;
  align-items: center;
  margin-top: 30rpx;
}
.picker{
  font-size: 30rpx;
  border: 1rpx solid #0A3E79;
  padding: 10rpx 40rpx;
  background-color: #FFFFFF;
  color: #0A3E79;
  font-weight: bold;
}
.sure_btn{
  background-color: #0A3E79;
  color: #ffffff;
  font-size: 105%;
  width: 90%;
  margin-top: 90rpx;
  text-align: center;
  height: 80rpx;
}

js

import { formatDate,getTimeLastWeek,getTimeLastMonth,getTimeThreeMonth,getTimeHalfYear } from "../../utils/util";
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    dateList: [{
        id: 1,
        value: '当天',
        flag: false
      },
      {
        id: 2,
        value: '近七天',
        flag: false
      },
      {
        id: 3,
        value: '近一个月',
        flag: false
      },
      {
        id: 4,
        value: '近三个月',
        flag: false
      },
      {
        id: 5,
        value: '近半年',
        flag: false
      }
    ],
    startDate: '',
    endDate: '',
    currentTime:formatDate(new Date()),
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 快速选择
     * @param {*} e 
     */
    handleQuickChoose(e) {
      let that = this;
      let item1 = e.currentTarget.dataset.item;
      that.data.dateList.forEach(item => {
        if (item.id === item1.id) {
          item.flag = true;
        } else {
          item.flag = false;
        }
      })
      that.setData({
        dateList: that.data.dateList
      })

      switch (item1.id) {
        case 1: //当天
          console.log(1,that.data.currentTime);
          that.setData({
            startDate:that.data.currentTime,
            endDate:that.data.currentTime
          })
          break;
        case 2: //近七天
          console.log(2);
          that.setData({
            startDate:getTimeLastWeek(new Date()),
            endDate:that.data.currentTime
          })
          break;
        case 3: //近一个月
          console.log(3);
          that.setData({
            startDate:getTimeLastMonth(new Date()),
            endDate:that.data.currentTime
          })
          break;
        case 4: //近三个月
          console.log(4);
          that.setData({
            startDate:getTimeThreeMonth(new Date()),
            endDate:that.data.currentTime
          })
          break;
        case 5: //近半年
          console.log(5);
          that.setData({
            startDate:getTimeHalfYear(new Date()),
            endDate:that.data.currentTime
          })
          break;
      }
      console.log(that.data.dateList);
      // console.log(e);
    },
    /**
     * 选择时间
     */
    bindDateChange(e) {
      console.log('picker发送选择改变,携带值为', e)
      let that = this;
      let type = e.currentTarget.dataset.type
      if (type == 1) {
        that.setData({
          startDate: e.detail.value
        })
      } else {
        that.setData({
          endDate: e.detail.value
        })
      }
    },
    /**
     * 顶部关闭按钮
     */
    onClose() {
      this.triggerEvent('sync', {
        show: false
      })
    },

    /**
     * 确定
     */
    handleSure() {
      let that = this;
      if(!that.data.startDate){
        app.myShowToast('开始时间不能为空');
        return false;
      }
      if(!that.data.endDate){
        app.myShowToast('结束时间不能为空');
        return false;
      }
      if(that.data.startDate <= that.data.endDate){
        that.triggerEvent('sync', {
          show: false,
          startDate: that.data.startDate,
          endDate: that.data.endDate
        })
      }else{
        app.myShowToast('结束时间不能小于开始时间');
        return false;
      }
    
    }
  },

})

工具类 不一定运算正确,有更好的可以继续实验 三个月 以及半年还未测试多种突发情况

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}


/**
 * 当天
 * @param {*} date 
 */
const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('-')  
}

/** 
* 时间戳转化为年 月 日 时 分 秒 
* number: 传入时间戳 
* format:返回格式,支持自定义,但参数必须与formateArr里保持一致 
*/
function formatTimeTwo(number, format) {
 
  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];
 
  var date = new Date(number * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));
 
  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));
 
  for (var i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}
 
/**
 * 近七天
 * @param {*} last 
 */
const getTimeLastWeek = last => {
  const year = last.getFullYear()
  const day = last.getDate()
  const ti = day - 7
  // 判断是否月初
  if (ti <= 0) {
    const month = last.getMonth() + 1 - 1
    const d = new Date(year, month, 0)
    const dayBig = d.getDate() //获取当月的所有天数
    const ti1 = dayBig + ti
    return [year, month, ti1].map(formatNumber).join('-')
  } else {
    const month = last.getMonth() + 1
    return [year, month, ti].map(formatNumber).join('-')
  }
  // return [year, month, day].map(formatNumber).join('-')

}

/**
 * 近1个月
 * @param {*} last 
 */
const getTimeLastMonth = last => {
  const year = last.getFullYear()
  const day = last.getDate()
  const ti = day - 30 
  // 判断是否月初
  if (ti <= 0) {
    const month = last.getMonth() + 1 - 1
    const d = new Date(year, month, 0)
    const dayBig = d.getDate() //获取当月的所有天数
    const ti1 = dayBig + ti
    return [year, month, ti1].map(formatNumber).join('-')
  } else {
    const month = last.getMonth() + 1
    return [year, month, ti].map(formatNumber).join('-')
  }
}

/**
 * 近3个月
 * @param {*} last 
 */
const getTimeThreeMonth = last => {
  const year = last.getFullYear()
  const month = last.getMonth() + 1
  const day = last.getDate()
  // 判断三个月的开始月份
  const startMonth = month - 3;
  // 判断是否是年初
  if(startMonth <= 0){
    year = year - 1 ;
  }
  return [year, startMonth, day].map(formatNumber).join('-')
}

/**
 * 近3个月
 * @param {*} last 
 */
const getTimeHalfYear = last => {
  const year = last.getFullYear()
  const month = last.getMonth() + 1
  const day = last.getDate()
  // 判断三个月的开始月份
  const startMonth = month - 6;
  // 判断是否是年初
  if(startMonth <= 0){
    year = year - 1 ;
  }
  return [year, startMonth, day].map(formatNumber).join('-')
}

/**
 * 赋0
 * @param {*} n 
 */
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

module.exports = {
  formatTime: formatTime,
  formatDate:formatDate,
  formatTimeTwo: formatTimeTwo,
  getTimeLastWeek:getTimeLastWeek,
  getTimeLastMonth:getTimeLastMonth,
  getTimeThreeMonth:getTimeThreeMonth,
  getTimeHalfYear:getTimeHalfYear
}

父视图

引入组件

## 引入
"datePicker":"../../../components/datePicker/index"

应用

<!-- 时间选择组件 bind:sync 子类回传数据的方法-->
<datePicker wx:if="{{show}}" bind:sync="syncGetDate"></datePicker>

js

 syncGetDate(e){
  let that = this;
  let show = e.detail.show; 
  if(!show){ // 子组件点击了关闭   关闭弹窗
    that.setData({
      show:false
    })
  }
  console.log("子组件:",e);
  // that.getPurchaseList();
}

子组件

标签:const,自定义,color,微信,date,组件,last,font,data
From: https://www.cnblogs.com/depressiom/p/16612755.html

相关文章

  • 2 Django-message组件
    假设:你正在做一个订单支付平台,其中用到了删除/撤销订单问题。想给予用户一些提示。可以用到Django的message组件。该组件通过第一次请求,写入提示信息并返回重定向,第二次请......
  • vue父传子属性命名和封装组件命名问题(巨坑)
    在vue的中文官网有这样的说明:HTML中的特性名是大小写不敏感的,所以浏览器会把所有大写字符解释为小写字符。这意味着当你使用DOM中的模板时,camelCase(驼峰命名法)的pr......
  • element-ui 城市选择组件
    <el-cascadersize="large":options="options"placeholder="请选择地区"expand-trigger="hover"ref="cascaderAddr"v-model="selectedOptions"@change......
  • Vue 组件通信之 Bus
    bus详细描述:vue中非父子组件之间通信除了使用vuex,也可以通过bus总线,两者适用场景不同。bus适合小项目、数据被更少组件使用的项目,对于中大型项目数据在很多组件之间使用......
  • 时间格式化之获取自定义前半个小时的时间
    前几天做项目发现一个很费事的事情,时间格式化问题,如果我要获取 2022-08-2211:42:32 半个小时的时间应该怎么写?发现了newData()的getTime()的方法,可以吧时间转化成m......
  • U8 V13.0小白入门开发记录四-------------------初识自定义按钮开发
    今天是第一次刚接触U8自定按钮开发,本人也是一名小白。网上的资料太少,就连一些开发文档都找不到。通过零零碎碎的测试和调研。发下一些基础并记录在此,如有补充请在下方评论,......
  • Vue面试题06:Vue子组件是否可以修改父组件的数据?
    Vue子组件是否可以修改父组件的数据?可以修改但不推荐:首先,文档中指出组件开发需要遵循单向数据流原则:即所有的props都遵循着单向绑定的原则,props因父组件的更新而变化......
  • 微信8.0.27正式更新,这4个功能太赞了!
    最近,安卓微信终于更新了8.0.27正式版,在正式版中带来了4个比较实用的功能,在个人信息保护、聊天记录备份、软件使用方便程度上都有不错的表现。下面我们就一起瞧瞧这些新功......
  • 同一个父组件,兄弟组件相互传参,调用
    组件brother2想调用组件brother1的方法,并传参可以新建一个handler.js文件importVuefrom'vue';exportdefaultnewVue();brother1组件方法:importhandlerfr......
  • vue3动态组件切换
    <template><divclass="goods-tabs"><nav><a@click='toggle("GoodsDetail")':class="{active:componentName==='GoodsDetail'}"href="javascript:;">商品详情</a>......