selectDatePicker.vue 2.22 KB
<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>