1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vue基礎:フィルター

Posted at

Vueでは日付フォーマットするなどの処理を「|」で簡単に記載できるのはフィルター機能です。
一般的なテキストフォーマットを適用するために使用できるフィルタを定義できます。
フィルタは、mustache 展開と v-bind 式 2 つの場所とも使用できます

フィルターの定義方法

1. コンポーネント内(ローカル)

コンポーネント内で定義する。
例:

filters: {
  formatDate: function (date) {
    if (!date) {
      return ''
    }
    moment.locale("ja");
    var d = moment.tz(date, "YYYYMMDDHHmm", "Asia/Tokyo");
    return d.format("M/D(ddd) HH:mm");
  }
}

2. 共通(グローバル)

main.jsの中で定義するなど
例:

Vue.filter('formatDate', function(date){
  if (!date) {
    return ''
  }
  moment.locale("ja");
  var d = moment.tz(date, "YYYYMMDDHHmm", "Asia/Tokyo");
  return d.format("M/D(ddd) HH:mm");
}

使用例

1. mustache 展開

{{ date| formatDate }}

2. v-bind 式

<div v-bind:label="date | formatDate"></div>

複数のフィルター

Shellのように連続フィルターをしたい場合は、下記のように複数のメソッドを設定できます。

{{ message | filterA | filterB }}

メソッドの呼び出し

メソッドは複数パラメータの場合はメソッド名ではなく、メソッドを呼び出す記載もOKです。

{{ message | filterA('arg1', arg2) }}

filterAは3つのパラメータがあるメソッドです。
例:

function filterA(message, param2, param3) {
  return  message + param2 + param3
}

参考URL:https://jp.vuejs.org/v2/guide/filters.html

以上

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?