vue-apps/com.actionsoft.apps.kms.mobile/components/fieldDate.vue

123 lines
3.4 KiB
Vue
Raw Normal View History

2025-07-07 13:55:22 +08:00
<template>
<div class="select">
<van-field
v-model="result"
v-bind="$attrs"
readonly
is-link
@click="show = !show"
/>
<van-popup v-model="show" position="bottom">
<!-- $attrs 可以把根节点的attr放到目标组件上如此可以像使用 DatePicker 组件一样使用这个新组件 -->
<van-datetime-picker
v-bind="$attrs"
:type="type"
title="请选择日期"
:min-date="minDate"
:max-date="maxDate"
@cancel="cancel"
@confirm="confirm"
/>
</van-popup>
</div>
</template>
<script>
export default {
name: 'VantFieldDate',
model: {
prop: 'selectValue'
},
props: {
type: {
type: String,
default: null
},
selectValue: {
type: [String, Number, Date],
default: undefined // 值不能是 nullDatePicker会报错
},
minDate: {
type: Date,
default: undefined
},
maxDate: {
type: Date,
default: undefined
},
// 展示的格式化
format: {
type: String,
default: null
}
},
data() {
return {
show: false
}
},
computed: {
// 展示的格式化时间提交的值是Date类型数据
formatFormula() {
if (this.format) {
return this.format
} else if (this.type === 'date') {
return 'yyyy-MM-dd'
} else if (this.type === 'datetime') {
return 'yyyy-MM-dd hh:mm'
} else if (this.type === 'time') {
return 'hh:mm'
} else if (this.type === 'year-month') {
return 'yyyy-MM'
}
},
result() {
return this.selectValue ? this.dateFormat(this.selectValue, this.formatFormula) : ''
}
},
methods: {
dateFormat: (value, format) => {
if (!value) return
if (!(value instanceof Date)) {
value = new Date(value)
}
let o = {
'M+': value.getMonth() + 1, // month
'd+': value.getDate(), // day
'h+': value.getHours(), // hour
'm+': value.getMinutes(), // minute
's+': value.getSeconds(), // second
'q+': Math.floor((value.getMonth() + 3) / 3), // quarter
'S': value.getMilliseconds() // millisecond
}
if (!format || format === '') {
format = 'yyyy-MM-dd hh:mm:ss'
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (value.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (let k in o) {
if (new RegExp('(' + k + ')').test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
}
}
return format
},
confirm(value) {
// 更新 v-model 绑定的 value 值,第二个参数是毫秒数,第三个参数是原始值,根据自己的项目的数据结构来修改
// input 事件同时也会触发 vee-validate 的验证事件
this.$emit('input', value.getTime(), value)
// onChange事件虽然重写 @input可以实现但这样会破坏 v-model 写法。
this.$emit('change', value.getTime(), value)
this.show = false;
},
cancel() {
this.$emit('cancelDate');
this.show = false
}
}
}
</script>