vant 时分秒选择组件封装
<template>
<div class="edit-time-picker">
<van-popup v-model="showPicker" round position="bottom">
<van-picker
ref="picker"
show-toolbar
:columns="columns"
@cancel="showPicker = false"
@confirm="onConfirm"
/>
</van-popup>
</div>
</template>
<script>
import { Picker, Popup } from 'vant';
Vue.use(Picker).use(Popup);
export default {
data() {
return {
showPicker: false,
columns: []
}
},
created() {
this.initColumns()
},
methods: {
initColumns() {
const list = []
const Hours = []
const Minutes = []
const Seconds = []
for (let i = 0; i<=23; i++) {
Hours.push(String(i).padStart(2, '0'))
}
for (let i = 0; i<=59; i++) {
Minutes.push(String(i).padStart(2, '0'))
Seconds.push(String(i).padStart(2, '0'))
}
list.push({
values: Hours,
defaultIndex: 0
})
list.push({
values: Minutes,
defaultIndex: 0
})
list.push({
values: Seconds,
defaultIndex: 0
})
this.columns = list
},
open(times) {
this.showPicker = true
console.log('times', times)
// 设置当前选中时间 19:23:33 格式
if(times) {
const initialTime = times.split(':')
if(initialTime.length === 3) {
this.$nextTick(() => {
this.$refs.picker && this.$refs.picker.setIndexes([Number(initialTime[0]), Number(initialTime[1]), Number(initialTime[2])])
})
}
} else {
// 当前时间
const date = new Date();
let hours = String(date.getHours()).padStart(2, '0') // 时
let minutes = String(date.getMinutes()).padStart(2, '0') // 分
let seconds = String(date.getSeconds()).padStart(2, '0') //秒
this.$nextTick(() => {
this.$refs.picker && this.$refs.picker.setIndexes([Number(hours), Number(minutes), Number(seconds)])
})
}
},
onConfirm(val) {
this.$emit('edit', val.join(':'))
}
},
}
</script>
// 使用方式
<time-picker ref="timePicker" />
this.$refs.timePicker.open('19:23:22')