forked from mengyxu/noob-components
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.6 KiB
57 lines
1.6 KiB
<template> |
|
<slot v-if="slot" :display="display" /> |
|
<template v-else>{{ display }}</template> |
|
</template> |
|
<script setup lang="ts"> |
|
import dayjs from "dayjs"; |
|
import { computed, toRef } from "vue"; |
|
import { watchEffectOnce } from "noob-mengyxu"; |
|
|
|
interface Props { |
|
value: string | number; |
|
valueFormat?: string; |
|
valueTz?: string; |
|
displayFormat?: string; |
|
locale?: string; |
|
type?: "iso8601" | "unix" | "unixMillis"; |
|
slot?: boolean; |
|
} |
|
|
|
const props = defineProps<Props>(); |
|
|
|
watchEffectOnce(toRef(props, "valueFormat"), async () => { |
|
const customParseFormat = await import("dayjs/plugin/customParseFormat"); |
|
dayjs.extend(customParseFormat.default); |
|
}); |
|
|
|
watchEffectOnce(toRef(props, "valueTz"), async () => { |
|
const timeZone = await import("dayjs/plugin/timezone"); |
|
dayjs.extend(timeZone.default); |
|
}); |
|
|
|
const parsed = computed(() => { |
|
if (props.type === "unix" || props.type === "unixMillis") { |
|
const value = typeof props.value === "string" ? parseFloat(props.value) : props.value; |
|
return props.type === "unix" ? dayjs.unix(value) : dayjs(value); |
|
} else { |
|
if (props.valueFormat && props.valueTz) { |
|
return dayjs.tz(props.value, props.valueFormat, props.valueTz); |
|
} else if (props.valueTz) { |
|
return dayjs.tz(props.value, props.valueTz); |
|
} else if (props.valueFormat) { |
|
return dayjs(props.value, props.valueFormat); |
|
} else { |
|
return dayjs(props.value); |
|
} |
|
} |
|
}); |
|
|
|
const display = computed(() => { |
|
let dt = parsed.value; |
|
if (props.locale) { |
|
dt = dt.locale(props.locale); |
|
} |
|
|
|
return dt.format(props.displayFormat); |
|
}); |
|
</script>
|
|
|