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 模組
  • 執行 pnpm dev 以開發模式啟動 playground

許可證

用 ❤️ 製作

根據 MIT 許可證釋出。