vuux
Version:
Vue3 Nuxt3 Nuxt4 组件库
56 lines (55 loc) • 1.6 kB
JavaScript
import { ref as d, computed as m, onMounted as D, onUnmounted as h } from "vue";
const M = (e) => {
const l = d(Date.now());
let o = null;
const t = m(() => {
if (e.time instanceof Date)
return e.time;
if (typeof e.time == "number")
return new Date(e.time);
if (typeof e.time == "string") {
if (/^\d+$/.test(e.time))
return new Date(parseInt(e.time));
const n = new Date(e.time);
return isNaN(n.getTime()) ? new Date(e.time.replace(/-/g, "/")) : n;
}
return /* @__PURE__ */ new Date("");
}), s = m(() => isNaN(t.value.getTime()) ? "无效的日期" : t.value.toLocaleString()), g = (n, w) => {
const r = Math.floor((w - n.getTime()) / 1e3);
if (r < 10)
return "刚刚";
if (r < 60)
return `${r}秒前`;
const u = Math.floor(r / 60);
if (u < 60)
return `${u}分钟前`;
const f = Math.floor(u / 60);
if (f < 24)
return `${f}小时前`;
const i = Math.floor(f / 24);
if (i === 1)
return "昨天";
if (i < 30)
return `${i}天前`;
const a = Math.floor(i / 30);
if (a === 1)
return "上个月";
if (a < 12)
return `${a}个月前`;
const c = Math.floor(a / 12);
return c === 1 ? "去年" : `${c}年前`;
}, v = m(() => isNaN(t.value.getTime()) ? "无效的日期" : g(t.value, l.value));
return D(() => {
e.autoUpdate && (o = window.setInterval(() => {
l.value = Date.now();
}, 60 * 1e3));
}), h(() => {
o && clearInterval(o);
}), {
fullTime: s,
relativeTime: v
};
};
export {
M as useTimeAgo
};