【小程序】封装时间选择组件:用单元格van-cell和插槽slot,包括起始时间和终止时间

效果

可以选择起始时间和终止时间,并显示。
时间选择器放在van-cell的value插槽中。

在这里插入图片描述
用的库:
https://vant-contrib.gitee.io/vant-weapp/#/home
https://dayjs.fenxianglu.cn/category/

用的组件:Cell单元格、DatetimePicker时间选择、Popup弹出层

"usingComponents": {
      "van-popup": "@vant/weapp/popup/index",
      "van-cell": "@vant/weapp/cell/index",
      "van-cell-group": "@vant/weapp/cell-group/index",
      "van-datetime-picker": "@vant/weapp/datetime-picker/index"
    }

代码

HTML

注意,这里的van-cell的value放的是时间选择器,以插槽的形式实现。

根据文档:这里要求用<view slot="">实现value的插槽,而不是<view slot="value"><view slot>

在这里插入图片描述
data-type用来在js方法中得知选择的是开始还是结束的时间。其他属性见文档。

<van-cell-group>
 <van-cell title="销售日期" border="{{ false }}" title-width="60px">
   <!-- value用slot,不能slot="value",不能slot,必须slot="" -->
   <view slot="">
     <view class="start timeItem inline-block" bindtap="showPopup" data-type="start">
       {{ date.start }}
     </view><view class="end timeItem inline-block" bindtap="showPopup" data-type="end">
       {{ date.end }}
     </view>
   </view>
 </van-cell>
</van-cell-group>

CSS

  .inline-block {
    /*让它们一行*/
    display: inline-block;
  }
  .timeItem {
    /*加点边框、间距*/
    margin: 0 4px;
    border: 1px solid #888;
    padding: 0 8px;
  }

JavaScript

会用到dayjs库。

data() {
  return {
    showPop: false,
    dataType: '',//选择的时间是开始还是结束
    date: {
          start: dayjs().format('YYYY-MM-DD'),
          end: dayjs().format('YYYY-MM-DD')
        },
    currentDate: new Date().getTime(),//在时间选择器选择的时间
    minDate: new Date().getTime()
  }
},
methods: {
	 //弹出
     showPopup(e) {
       this.showPop = true
       //在弹出框后得知是开始/结束
       this.dataType = e.currentTarget.dataset.type
     },
	 //关闭
     colsePopup() {
       this.showPop = false
     },
	 //选择的时间赋值
     timeInput(event) {
       this.currentDate = event.detail
     },
	 //点击“确认”后
	 timeConfirm() {
        // currentDate是时间戳(毫秒)
        if (this.dataType === 'start') {
          this.date.start = dayjs(this.currentDate).format('YYYY-MM-DD')
        } else {
          this.date.end = dayjs(this.currentDate).format('YYYY-MM-DD')
        }
        this.colsePopup()
      }
   }

其他

这个功能感觉很常见,记录一下。
只是记录自己敲码的过程,水平很烂。
功能并不完善,比如没有end必须>=start的判断等。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

karshey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值