【小程序】封装时间选择组件:用单元格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的判断等。