Vue.js

Nuxt.jsでmoment.jsを使う方法

この記事の目次
  1. Nuxt.jsでmoment.jsを使う方法
  2. moment.jsをインストール
  3. Vue.filter()を使用してカスタマイズしたフィルタを登録する
  4. nuxt.config.jsの設定を変更する
  5. templateタグで使う

Nuxt.jsでmoment.jsを使う方法を紹介します。

Nuxt.jsでmoment.jsを使う方法

moment.jsをインストール


npm install moment

Vue.filter()を使用してカスタマイズしたフィルタを登録する

まずはカスタマイズしたフィルタを登録するためのフォルダとファイルを作成します。
pluginsフォルダにfilters.jsを作成します。

そして、vueとmoment.jsをimportします。

import Vue from 'vue'
import moment from 'moment'

そして、Vue.filter()を使用してカスタマイズしたフィルタを登録します。

Vue.filter('formatDate', (value) => {
  if(!value) return ''
  return moment(value).locale('ja').format('llll')
})

日本語の場合だと次のような例があります。

Format Dates
moment().format('MMMM Do YYYY, h:mm:ss a'); // 4月 30日 2021, 8:45:23 午後
moment().format('dddd');                    // 金曜日
moment().format("MMM Do YY");               // 4月 30日 21
moment().format('YYYY [escaped] YYYY');     // 2021 escaped 2021
moment().format();                          // 2021-04-30T20:45:23+09:00
Relative Time
moment("20111031", "YYYYMMDD").fromNow(); // 10年前
moment("20120620", "YYYYMMDD").fromNow(); // 9年前
moment().startOf('day').fromNow();        // 21時間前
moment().endOf('day').fromNow();          // 3時間後
moment().startOf('hour').fromNow();       // 1時間前
Calendar Time
moment().subtract(10, 'days').calendar(); // 2021/04/20
moment().subtract(6, 'days').calendar();  // 先週土曜日 20:45
moment().subtract(3, 'days').calendar();  // 火曜日 20:45
moment().subtract(1, 'days').calendar();  // 昨日 20:45
moment().calendar();                      // 今日 20:45
moment().add(1, 'days').calendar();       // 明日 20:45
moment().add(3, 'days').calendar();       // 来週月曜日 20:45
moment().add(10, 'days').calendar();      // 2021/05/10
Multiple Locale Support
moment.locale();         // ja
moment().format('LT');   // 20:45
moment().format('LTS');  // 20:45:23
moment().format('L');    // 2021/04/30
moment().format('l');    // 2021/04/30
moment().format('LL');   // 2021年4月30日
moment().format('ll');   // 2021年4月30日
moment().format('LLL');  // 2021年4月30日 20:45
moment().format('lll');  // 2021年4月30日 20:45
moment().format('LLLL'); // 2021年4月30日 金曜日 20:45
moment().format('llll');

詳しくはmoment.jsの公式サイトで確認できます。

nuxt.config.jsの設定を変更する

nuxt.config.jsのpluginsに追記します。

'@/plugins/filters'

上の場合rootのpluginsフォルダの中のfilters.jsという意味になります。

templateタグで使う

created {{ dateCreated | formatDate }}

などとしてカスタマイズしたフィルターのformatDateを指定します。