import { createApp, h, ref } from 'vue'; import xDateSelect from './index.vue'; import dayjs from "dayjs"; //根据传入的日期格式和日期 生成对应的时间戳 function generateTimestamp(format, date) { // 直接使用传入的 format 字符串作为解析格式 const dateStr = dayjs(date, format); if (!dateStr.isValid()) { throw new Error('Invalid date'); } return dateStr.valueOf(); // 返回时间戳 } let datePickerApp = null; let container=null export function openDatePicker(options = {}) { // 如果已经存在一个日期选择器实例,先销毁它 if (datePickerApp) { datePickerApp.unmount(); datePickerApp = null; // 防止重复销毁 } if (container){ //清除dom document.body.removeChild(container); } // 创建日期选择器实例 datePickerApp = createApp({ setup() { const showdate = ref(true) // 处理确认事件 const handleConfirm = (value) => { options?.onConfirm?.(dayjs(value).format(options.format)); // 使用可选链调用 showdate.value = false; // 关闭日期选择器 }; return () => h(xDateSelect, { ...options, defaultValue: generateTimestamp(options.format, options.value), 'onUpdate:show': (newValue) => { showdate.value = newValue; if (!newValue) { datePickerApp?.unmount(); // 确保不会重复销毁 datePickerApp = null; } }, onConfirm: handleConfirm, show: showdate.value, }); } }) container = document.createElement('div'); document.body.appendChild(container); datePickerApp.mount(container); }