LoginSignup
6
3

More than 3 years have passed since last update.

【Nuxt.js】dayjs導入編:リアルタイムな日時を表示してみよう

Posted at

前置き

dayjsについて🗓🕰
日付と時刻を表示・操作できるライブラリ🎈🧸

今回は簡単に表示のみ。
時間の足し引きなどは
TypeScriptで設定が必要なため、
TypeScriptの応用編をやってからですね!

公式
https://www.npmjs.com/package/dayjs
日本語
https://github.com/iamkun/dayjs/blob/master/docs/ja/README-ja.md

使用ファイル

file
pages/
--| index.vue

plugins/
--| day.js

nuxt.config.js

Step1: インストール

ターミナル
npm i dayjs

Step2:  /pluginsにjsファイルを追加

plugins/day.jsを作成
Nuxt.jsにおけるプラグインの書き方
https://ja.nuxtjs.org/guide/plugins/

plugins/day.js
import dayjs from 'dayjs'

export default ({ app }, inject) => {
   inject('dayjs', ((string) => dayjs(string)))
}

Step3: nuxt.config.jsのpluginsに記載

これでグローバル登録

nuxt.config.js
plugins: [
 '~plugins/day.js'
],

step4: 表示

1番シンプルなdayjs().format()で表示🍒
スクリーンショット 2020-01-27 17.09.06.png

◾️パターン1

index.vue
<template>
 <div class="page">
   <p v-text="$dayjs().format('YYYY-MM-DD')" />
 </div>
</template>

<script>
</script>

◾️パターン2

index.vue
<template>
 <div class="page">
   <p>
     {{ now }}
   </p>
 </div>
</template>
<script>
export default {
 data () {
   return {
     now: '',
   }
 },
 mounted(){
   this.now = this.$dayjs().format('YYYY-MM-DD')
 },
}
</script>

表示パターン色々

◾️曜日、時刻も表示

デフォルトは英語(US)ロケール。
後ほど日本語に変更していきます🌟
スクリーンショット 2020-01-27 17.33.18.png

index.vue
<template>
 <div class="page">
   <p v-text="$dayjs().format('dddd, MMMM D, YYYY h:mm A')" />
 </div>
</template>

<script>
</script>

長いのでFormatを使います🍒
plugins/day.jsを編集

plugins/day.js
import LocalizedFormat from 'dayjs/plugin/localizedFormat'

dayjs.extend(LocalizedFormat)

dayjs().format('L LT')

書き換え

index.vue
<template>
 <div class="page">
   <p v-text="$dayjs().format('LLLL')" />
 </div>
</template>

<script>
</script>

表示は変わりません🌟
スクリーンショット 2020-01-27 17.33.18.png

◾️日本語で表示
スクリーンショット 2020-01-27 17.39.39.png

plugins/day.jsを編集

plugins/day.js
import dayjs from 'dayjs'

// 日本語表示にするためlocaleを追加
import 'dayjs/locale/ja'
dayjs.locale('ja')

export default ({ app }, inject) => {
   inject('dayjs', ((string) => dayjs(string)))
}

templateを編集

index.vue
<template>
 <div class="page">
   <p v-text="$dayjs().locale('ja').format('LLLL')" />
 </div>
</template>

<script>
</script>

jaを他のロケールに変えれば
簡単に表示が変わります♪

記事が公開したときにわかる様に、
Qiita・Twitterフォローをお願いします😀
https://twitter.com/aLizlab

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3