UNPKG

@zhsz/cool-design-dv

Version:

133 lines (132 loc) 3.71 kB
import { defineComponent, useSlots, ref, computed, watch, onBeforeUnmount, openBlock, createElementBlock, createElementVNode, normalizeClass, unref, renderSlot, createCommentVNode, createTextVNode, toDisplayString } from "vue"; import "./style.css"; import dayjs from "dayjs"; import relativeTime from "dayjs/plugin/relativeTime"; import "dayjs/locale/zh-cn"; const _hoisted_1 = { class: "my-dv-date" }; const _hoisted_2 = { key: 0 }; const _hoisted_3 = { class: "my-date__value" }; const _hoisted_4 = { key: 1 }; const __default__ = defineComponent({ name: "DvDate" }); const _sfc_main = /* @__PURE__ */ defineComponent({ ...__default__, props: { // 原始值 value: [String, Number, Date], // 默认值 defaultValue: { type: [String, Number, Date], default() { return null; } }, // 显示格式, 对相对时间无效 format: { type: String, default: "YYYY-MM-DD HH:mm:ss" }, // 启用相对时间模式 relative: Boolean, // 颜色 type: { type: String, validator(val) { return ["", "primary", "success", "warning", "danger", "info"].includes( val ); } }, // 时间保持实时更新, 对相对时间无效 tick: Boolean }, setup(__props) { dayjs.extend(relativeTime); dayjs.locale("zh-cn"); const $slots = useSlots(); const props = __props; const timerId = ref(); const dayInstance = ref(); const classes = computed(() => { return { "my-date": true, [`is-${props.type}`]: !!props.type }; }); const displayValue = computed(() => { if (!dayInstance.value) return ""; if (props.relative) { return dayInstance.value.fromNow(); } return dayInstance.value.format(props.format); }); function init() { let instance = dayjs(props.value); if (!instance.isValid()) { instance = props.defaultValue ? dayjs(props.defaultValue) : null; } dayInstance.value = instance; props.tick ? start() : stop(); } function start() { if (!dayInstance.value) return; clearInterval(timerId.value); timerId.value = setInterval(() => { dayInstance.value = dayInstance.value.add(1, "second"); }, 1e3); } function stop() { clearInterval(timerId.value); timerId.value = null; } watch( () => props.value, () => { stop(); init(); }, { immediate: true } ); watch( () => props.tick, (val) => { val ? start() : stop(); } ); onBeforeUnmount(() => { stop(); dayInstance.value = null; }); return (_ctx, _cache) => { return openBlock(), createElementBlock("div", _hoisted_1, [ createElementVNode("div", { class: normalizeClass(classes.value) }, [ unref($slots).prefix ? (openBlock(), createElementBlock("span", _hoisted_2, [ renderSlot(_ctx.$slots, "prefix") ])) : createCommentVNode("", true), createElementVNode("span", _hoisted_3, [ renderSlot(_ctx.$slots, "default", { value: __props.value, displayValue: displayValue.value, dayjs: unref(dayjs) }, () => [ createTextVNode(toDisplayString(displayValue.value), 1) ]) ]), unref($slots).suffix ? (openBlock(), createElementBlock("span", _hoisted_4, [ renderSlot(_ctx.$slots, "suffix") ])) : createCommentVNode("", true) ], 2) ]); }; } }); export { _sfc_main as default };