通过 100+ 技巧学习 Nuxt!

nuxt-time

使用 Nuxt 安全地在服务器上渲染本地日期和时间

Nuxt Time

npm versionnpm downloadsGithub ActionsCodecov

用于 Nuxt 的 SSR 安全时间元素

特性

  • ✨ SSR/SSG 安全渲染任何日期/时间
  • 💪 防止客户端水合不匹配
  • 🏁 尊重浏览器区域设置
  • ✅ 渲染语义化的 <time> 元素

安装

安装并添加 nuxt-time 到你的 nuxt.config

npx nuxi@latest module add time
export default defineNuxtConfig({
  modules: ['nuxt-time'],
})

用法

要使用,你可以在你的应用程序中的任何地方使用 <NuxtTime> 组件。它将渲染一个符合规范的 <time> 元素。

它接受 datetimelocale (可选) 属性,以及 Intl.DateTimeFormat 接受的任何属性 (参见 MDN 参考)。 注意: 你可以通过 datetime 提供 Datenumber (例如 Date.now()),它将被正确渲染为 ISO 格式的日期。

<template>
  <!--
    Date.now() will safely respect the time on the server, not on the
    client. What's more, there will be no flash between server
    and client locale formatting.
  -->
  <NuxtTime :datetime="Date.now()" second="numeric" month="long" day="numeric" />
</template>

相对时间格式化

Nuxt Time 还支持使用 Intl.RelativeTimeFormat API 进行相对时间格式化。你可以通过将 relative 属性设置为 true 来启用此功能。

<template>
  <!--
    This will display the time relative to the current time, e.g., "5 minutes ago"
  -->
  <NuxtTime :datetime="Date.now() - 5 * 60 * 1000" relative />
</template>

💻 开发

  • 克隆此仓库
  • 使用 corepack enable 启用 Corepack
  • 使用 pnpm install 安装依赖
  • 使用 pnpm dev:prepare Stub 模块
  • 运行 pnpm dev 以在开发模式下启动 playground

许可证

用 ❤️ 制作

根据 MIT 许可证 发布。