LoginSignup
1
2

More than 3 years have passed since last update.

Vueでmoment.jsの使い方

Posted at

はじめに

この記事はVue触りたての筆者のメモのようなものです。

やりたいこと

データベースからとってきたデータを表示するときにtimestampを"YYYY/MM/DD HH:mm"のフォーマットに直したい

Vueでmomentの使い方

以下のタグをHTMLに追加します。

index.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js" type="text/javascript"></script>

あとは行いたい処理をかけばok!
筆者は日付の変換が行いたかったため以下のような処理を書きました。

index.html
<div class="ui segments" v-if="posts.length > 0">
      <div class="ui segment" v-for="post in posts">
      <h2>
      <div class="header">{{ post.userId }}</div>
      </h2>
      <!--index.jsで定義した日付の変換をする関数の呼び出し-->
   <!--{{ 関数に渡したい値 | 関数 }} とすることで関数に引数を渡すことができる-->
      {{ post.timestamp | moment  }}
      <div class="ui sub header">{{ post.text }}</div>
      <div class="ui grey label">{{ post.category }} 
    </div>
  </div>
</div>
index.js
var vm = new Vue({
    el: "#app", // Vue.jsを使うタグのIDを指定
    //日付を変換するフィルターの定義
    filters: {
        moment: function (date) {
            return moment(date).format('YYYY/MM/DD HH:mm');// eslint-disable-line
        }
    },
    //いろんな処理…
})

落とし穴

スクリプトタグを書く位置に注意!
※必ずmoment()を使いたいJSファイルを読み込むscriptタグより前に書かないとエラーを吐かれる

うまくいく例

index.html
<body>
    <!--momentの読み込みは必ず先に!-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js" type="text/javascript"></script>

    <!--momentを使いたいjsの読み込み-->
    <script src="./js/index.js" charset="utf-8"></script>
</body>

失敗する例

index.html
<body>
  <!--momentを使いたいjsの読み込み-->
    <script src="./js/index.js" charset="utf-8"></script>

    <!--momentの読み込み-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js" type="text/javascript"></script>
</body>

終わりに

今回の内容は恐らく超基本的なモノだと思います。
筆者はスクリプト言語を触るのがほぼ初めてだったためコードの上から順に読み込まれるということをすっかり忘れてて1日中ハマり続けました笑

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