selectDropdown.vue 2.82 KB
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";

const props = defineProps({
	item: {
		type: Object,
		default: () => {},
	},
	carTypeList: {
		type: Array,
		default: () => {},
	},
});

const emit = defineEmits(["update"]);
const showPicker = ref(false);
const pickerValue = ref([]);

const displayValueText = computed({
	get: () => String(props.item.valueText ?? ""),
	set: (v: string) => {
		if (!v) {
			emit("update", { value: "", valueText: "", valueKey: "" });
			return;
		}
		emit("update", {
			value: String(props.item.value ?? ""),
			valueText: v,
			valueKey: String(props.item.valueKey ?? ""),
		});
	},
});


// 页面加载时初始化数据
onMounted(() => {
	initData();
});

// 初始化数据
function initData() {
	pickerValue.value = [];
	if (props?.item?.inspectionResultVO) {
		const inspectionValueList = props?.item?.inspectionResultVO?.inspectionValueList || [];
		if (inspectionValueList && inspectionValueList.length > 0 && inspectionValueList[0].valueKey) {
			pickerValue.value = [inspectionValueList[0].valueKey];
		}
	}
	onConfirm();
}

// 计算属性
const columnsList = computed(() => {
	const optionsList = JSON.parse(props.item.options || "[]").map(item => {
		const valueList = (item || "").split("-");
		return {
			text: valueList[1] || "",
			value: valueList[0] || "",
		};
	});
	return props.item.nodeName === "车型" ? props.carTypeList : optionsList;
});



function onConfirm() {
	const picker = pickerValue.value && pickerValue.value.length > 0 ? pickerValue.value[0] : "";
	showPicker.value = false;
	const selected = columnsList.value.find((col) => col.value === picker) || {};
	emit("update", {
		value: selected.value || "",
		valueText: selected.text || "",
		valueKey: selected.value || "",
	});
}

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="displayValueText"
                   clearable
                   is-link
                   :label="item.nodeName"
                   name="datePicker"
                   :placeholder="item.placeholder"
                   readonly
                   :required="item.required === 1"
                   @click="showPicker = true" 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-picker v-model="pickerValue"
                        :columns="columnsList"
                        :title="item.nodeName"
                        @cancel="showPicker = false"
                        @confirm="onConfirm" />
        </van-popup>
    </div>
</template>

<style lang="scss" scoped></style>