Day.js Nuxt 模組
快速 2kB 的 Moment.js 替代方案,具有相同的現代 API
Day.js Nuxt 模組,支援 v3
功能
- ⛰ Nuxt 3 就緒
- 🚠 啟用任何可用的插件或語言環境
- 🌲 指定預設語言環境和時區
快速設定
- 將
dayjs-nuxt
依賴項新增至您的專案
npx nuxi@latest module add dayjs
- 將
dayjs-nuxt
新增至nuxt.config.ts
的modules
區段
export default defineNuxtConfig({
modules: [
'dayjs-nuxt'
]
})
基本用法
您可以使用提供的 $dayjs
在模板中存取 Day.js。
<template>
<div>
<time :datetime="$dayjs('2023-01-01').utc().toString()"> {{ date }} </time>
</div>
</template>
組合式函式
您可以使用 useDayjs 組合式函式在任何地方存取 Day.js。
<script setup>
import { useDayjs } from '#dayjs' // not need if you are using auto import
const dayjs = useDayjs()
dayjs.locale('fr')
dayjs.extend(...)
</script>
設定
您可以指定任意數量的語言環境、插件,設定預設語言環境,以及設定預設時區
export default defineNuxtConfig({
modules: ['dayjs-nuxt'],
dayjs: {
locales: ['en', 'fr'],
plugins: ['relativeTime', 'utc', 'timezone'],
defaultLocale: 'en',
defaultTimezone: 'America/New_York',
}
})
預設情況下,我們包含 relativeTime 和 utc 插件,並始終匯入 updateLocale
外部插件
export default defineNuxtConfig({
modules: ['dayjs-nuxt'],
dayjs: {
...
externalPlugins: [{
name: 'dayjsBusinessDays',
package: 'dayjs-business-days2',
option: {
holidays: [`2023-12-26`],
holidayFormat: `YYYY-MM-DD`,
}
}]
...
}
})
可選的 defaultLocale 自訂
除了在 defaultLocale:
中使用語言環境字串外,您還可以定義一個包含自訂語言環境的陣列。請參閱 dayjs 自訂 以取得更多資訊。
這裡有一個 relativeTime 設定的範例,讓我們建立一個咕嚕能理解的設定
export default defineNuxtConfig({
modules: ['dayjs-nuxt'],
dayjs: {
...
defaultLocale: ['en', {
relativeTime: {
future: "in %s",
past: "%s ago",
s: 'a few secondses',
m: "a minute",
mm: "%d minuteses",
h: "an hour",
hh: "%d hourses",
d: "a day",
dd: "%d dayses",
M: "a month",
MM: "%d monthseses",
y: "a year",
yy: "%d yearseses"
}
}]
...
}
})
開發
# Install dependencies
npm install
# Generate type stubs
npm run dev:prepare
# Develop with the playground
npm run dev
# Build the playground
npm run dev:build
# Run ESLint
npm run lint
# Run Vitest
npm run test
npm run test:watch
# Release new version
npm run release