在vant 中 dateTimePicker 和 popup 是分开的,如果想实现一个完整的时间选择器,必须要要对piker和popup进行重新封装,vs-date-picker是对它们的一个简单的二次封装。可根据自己的需要随意增删。
- vs-date-picker API
- vs-date-picker 使用代码演示
<van-cell title='选择时间' :value='dateTxt' is-link @click='openPicker' />
<VsDatePicker
v-model='show'
type='year-month'
:currentDate='currentDate'
@change='changeData' />
<script>
import VsDatePicker from '../../components/weight/vsDatePicker'
import { parseTime } from '../../utils'
export default {
name: 'DatePickerPage',
components: {
VsDatePicker
},
data() {
return {
show: false,
currentDate: ''
}
},
computed: {
dateTxt: function() {
return this.currentDate
? parseTime(this.currentDate, '{y}-{m}')
: this.currentDate
}
},
methods: {
openPicker() {
this.show = true
},
changeData(val) {
this.currentDate = val
}
}
}
</script>
- vs-date-picker 组件源码
新建一个名有 vs-date-picker.vue文件,代码如下:
<template>
<!-- van-poppup 使用:value的绑定形式为了防止在click-overlay的时候出现修改子组件修改prop值出现的报错问题 -->
<van-popup :value='value' position='bottom' @click-overlay='chosePiker'>
<van-datetime-picker
ref='picker'
v-model='choiceTime'
:type='$attrs.type'
:title='$attrs.title'
:min-date='minMaxDate[0]'
:max-date='minMaxDate[1]'
:formatter='formatter'
@confirm='changeDate'
@cancel='chosePiker'
/>
</van-popup>
</template>
<script>
export default {
name: 'DatePicker',
props: {
value: {
type: Boolean,
default: false
},
// 可选择的时间范围 1:不指定默认:2002/5-至今 2:只指定开始时间:开始时间-至今 3:自定义
timeRange: {
type: Array,
default: () => []
}
},
data() {
return {
choiceTime: ''
}
},
computed: {
minMaxDate: function() {
// Vant with minDate and maxDate must date type
let { timeRange } = this
if (timeRange.length) {
if (!timeRange[1]) timeRange[1] = new Date()
timeRange[0] = timeRange[0] instanceof Date ? timeRange[0] : new Date(timeRange[0].replace(/-/g, '/'))
timeRange[1] = timeRange[1] instanceof Date ? timeRange[1] : new Date(timeRange[1].replace(/-/g, '/'))
if (isNaN(timeRange[0].getTime()) || isNaN(timeRange[1].getTime())) throw new Error('timeRange时间格式错误!')
} else {
timeRange = [new Date('2002-05'), new Date()]
}
return timeRange
}
},
created() {
this.choiceTime = this.$attrs.currentDate
},
methods: {
formatter(type, val) {
if (type === 'year') {
return `${val}年`
} else if (type === 'month') {
return `${val}月`
} else if (type === 'day') {
return `${val}日`
} else if (type === 'hour') {
return `${val}时`
} else if (type === 'minute') {
return `${val}分`
}
return val
},
changeDate(val) {
this.$emit('input', false)
this.$emit('change', val)
},
chosePiker() {
this.choiceTime = this.$attrs.currentDate
setTimeout(() => {
this.$emit('input', false)
}, 0)
}
}
}
</script>
<style scoped>
</style>