Nuxt.js day.jsを使って日付処理を行う手順

Nuxt.js day.jsを使って日付処理を行う手順

nuxt.jsで 日付処理の軽量ライブラリであり、かつ「Moment.js」との互換性もある 「day.js」を利用して、日付処理を行うまでの簡単な手順とサンプルコードです。

環境

  • OS  ubuntu19.10
  • node v12.13.0
  • npm 6.12.1
  • Nuxt.js v2.10.2

Nuxt.jsはnpx create-nuxt-appでインストールしてます。

Moment.jsインストール

下記のコマンドでインストールします。

yarn add dayjs

day.js 使い方

plugins配下にdayjs.jsを下記のコードで追加します。

import 'dayjs/locale/ja'
import dayjs from 'dayjs'
import Vue from 'vue'

dayjs.locale('ja')

Vue.prototype.$dayjs = dayjs

次に nuxt.config.jsの pluginsにも登録します。

plugins: [
    { src: '~/plugins/dayjs', ssr: false }
  ],

最後にpages配下のindex.vueを下記のように編集します。

<template>
  <div class="container">
    <div>
      <logo />
      <h2 class="subtitle">
        現在日付
      </h2>
      <h2 class="subtitle">
      {{ now }} 
      </h2>
      </div>
    </div>
  </div>
</template>

<script>
import Logo from '~/components/Logo.vue'

export default {
  components: {
    Logo
  },
  data: () => ({
    now: ""
  }),
  mounted() {
    this.now = this.$dayjs().format('YYYY-MM-DD')
  }
}
</script>

<style>
.container {
  margin: 0 auto;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.title {
  font-family: 'Quicksand', 'Source Sans Pro', -apple-system, BlinkMacSystemFont,
    'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  display: block;
  font-weight: 300;
  font-size: 100px;
  color: #35495e;
  letter-spacing: 1px;
}

.subtitle {
  font-weight: 300;
  font-size: 42px;
  color: #526488;
  word-spacing: 5px;
  padding-bottom: 15px;
}

.links {
  padding-top: 15px;
}
</style>

起動します

yarn dev

ブラウザから http://localhost:3000/にアクセスすると現在日付がformatされて表示されます。