2
2

More than 3 years have passed since last update.

Vue3で moment.js を使いたい!

Posted at

Vue3.xで、moment.jsを使いたかった人のメモです。良い感じに日付整形したり演算できたりするようになるJSのライブラリですね。
※後から気づいたのですが、Vueのライブラリでvue-momentなるものがあり、こちらも候補に入れたかったなぁと思っています。

install

まずはインストールします。

$ npm install moment --save   # ← npm
$ yarn add moment             # ← yarn

usage

たとえば、以下のように書けます。
Vue2.xのコードを参考にするとfiltersを使っていることがありますが、Vue3では使えないので、以下はmethodsに書いています。

<template>
  <div>
    <div>
      {{ moment(new Date, 'MMMM Do YYYY, h:mm:ss a') }}
    </div>
  </div>
</template>

<script>
import moment from 'moment';

export default {
  methods: {
    moment(date, format) {
      return moment(date).format(format)
    }
  }
}
</script>

マスタッシュが展開されると、view上は以下のようになります。※時間帯はご愛嬌です。

July 24th 2021, 3:08:28 am

format例は公式はもちろん、「全61件!Moment.js日付フォーマット実例」なども参考にさせていただこうと思います。

2
2
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
2
2