vue之vant封装DatetimePicker 时间选择
代码如下
<template>
<div @click="onCancel" class="range-date">
<van-popup
v-model="showPopupvalue"
@click.stop
round
position="bottom"
:style="{ height: '80%' }"
>
<header class="header">
<div class="h-left" @click="onCancel">取消</div>
<div class="h-center">{{ title }}</div>
<div class="h-right" @click="onConfirm">确认</div>
</header>
<van-datetime-picker
title="开始日期"
v-model="startDate"
:type="type"
:min-date="minDate"
:formatter="formatter"
visible-item-count="4"
@change="startChange"
/>
<van-datetime-picker
title="结束日期"
v-model="endDate"
:type="type"
:min-date="endMinDate"
:formatter="formatter"
visible-item-count="4"
/>
</van-popup>
</div>
</template>
<script>
import { parseTime } from '@/utils'
export default {
name: 'Datetime',
components: {},
props: {
showPopup: {
type: Boolean,
default: false,
},
title: {
type: String,
default: '',
},
type: {
type: String,
default: 'date',
},
},
data() {
return {
showPopupvalue: this.showPopup,
minDate: new Date(2019, 0, 1),
endMinDate: new Date(),
startDate: new Date(),
endDate: new Date(),
}
},
watch: {
showPopup(val) {
this.showPopupvalue = val
},
},
methods: {
onConfirm() {
this.showPopupvalue = false
let value = [
parseTime(this.startDate, '{y}-{m}-{d}'),
parseTime(this.endDate, '{y}-{m}-{d}'),
].join(' - ')
this.$emit('onConfirm', { value: value, falg: false })
},
onCancel() {
this.showPopupvalue = false
this.$emit('onCancel', false)
},
startChange() {
let tmpDate = new Date(this.endDate)
this.endMinDate = new Date(this.startDate)
setTimeout(() => {
if (new Date(tmpDate).getTime() > new Date(this.endMinDate).getTime()) {
this.endDate = tmpDate
} else {
this.endDate = this.endMinDate
}
}, 0)
},
formatter(type, val) {
if (type === 'year') {
return `${val}年`
} else if (type === 'month') {
return `${val}月`
} else if (type === 'day') {
return `${val}日`
}
return val
},
},
}
</script>
<style lang="scss" >
.range-date {
.van-checkbox-group {
display: flex;
flex-direction: column;
padding-top: 1rem;
justify-content: center;
min-height: 5rem;
.van-checkbox {
height: 0.88rem;
justify-content: center;
font-size: 0.3rem;
}
}
.van-datetime-picker {
margin-top: 1.3rem;
& + .van-datetime-picker {
margin-top: 0.68rem;
}
.van-picker__toolbar {
height: 0.66rem;
color: #36395c;
font-size: 0.3rem;
background-color: #f5f6fb;
margin: 0 0.3rem;
justify-content: center;
button {
display: none;
}
}
}
}
</style>
<style lang="scss" scoped>
.header {
position: fixed;
background-color: #fff;
z-index: 99;
width: 100%;
max-width: 450px;
left: 0;
right: 0;
margin: 0 auto;
height: 0.88rem;
padding: 0 0.3rem;
border-radius: 0.24rem 0.24rem 0 0;
display: flex;
justify-content: space-between;
align-items: center;
.h-left,
.h-right {
font-size: 0.28rem;
}
.h-left {
color: #969799;
}
.h-right {
color: #576b95;
}
.h-center {
font-size: 0.32rem;
}
}
</style>
效果如下
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/58bfbddd53de1a9ddbd919c0ceda8a82.png)