selectDatePicker.vue
2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
const props = defineProps({
item: {
type: Object,
default: () => { },
},
});
const emit = defineEmits(["update"]);
const displayValue = computed({
get: () => String(props.item.value ?? ""),
set: (v: string) => emit("update", v),
});
const columnsType = ref(["year", "month", "day"]);
const showPicker = ref(false);
const pickerValue = ref([]);
// 页面加载时初始化数据
onMounted(() => {
initData();
});
// 初始化数据
function initData() {
const validationRules = JSON.parse(props.item.validationRules || "{}");
if (validationRules.datePattern && validationRules.datePattern.length > 8) {
columnsType.value = ["year", "month", "day"];
} else {
columnsType.value = ["year", "month"];
}
}
function handleShowPicker() {
showPicker.value = true;
if (!props.item.value) {
const date = new Date();
if (columnsType.value.length === 2) {
pickerValue.value = [date.getFullYear(), date.getMonth() + 1];
} else {
pickerValue.value = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
}
} else {
const dateArr = props.item.value.split("-");
if (columnsType.value.length === 2) {
pickerValue.value = [dateArr[0], dateArr[1]];
} else {
pickerValue.value = dateArr;
}
}
}
function onConfirm() {
let picker = "";
if (pickerValue.value.length > 0) {
picker = pickerValue.value.join("-");
}
showPicker.value = false;
emit("update", picker);
}
function getLabelWidth(nodeName: string) {
let widtPx = 76;
if (nodeName.length > 4) {
widtPx = widtPx + ((nodeName.length - 4) * 12);
}
return widtPx;
}
</script>
<template>
<div>
<van-field v-model="displayValue" clearable is-link :label="item.nodeName" name="datePicker"
:placeholder="item.placeholder" readonly :required="item.required === 1" @click="handleShowPicker"
input-align="right" :label-width="getLabelWidth(item.nodeName) + 'px'" />
<van-popup v-model:show="showPicker" destroy-on-close position="bottom" teleport="#vant-portal-host">
<van-date-picker v-model="pickerValue" :columns-type="columnsType" :title="item.nodeName"
@cancel="showPicker = false" @confirm="onConfirm" />
</van-popup>
</div>
</template>
<style lang="scss" scoped></style>