LoginSignup
0
1

More than 3 years have passed since last update.

【Nuxt.js】Vue.filter()で文字列整形

Posted at

Fiter()で文字列の整形

グローバルな Vue.filter() を使用してカスタマイズしたフィルタを登録します。
コードは'/plugins'ディレクトリの中に作成。
今回は日付をフィルターにかけて文字列を整形してみます。

plugins/filter.js
import Vue from 'vue'

//定数monthsに月名を文字列で用意
const months = [
  "1月",
  "2月",
  "3月",
  "4月",
  "5月",
  "6月",
  "7月",
  "8月",
  "9月",
  "10月",
  "11月",
  "12月"
];

const dateFilter = value => {
  return formatDate(value);
};

function formatDate(inputDate) {
  const date = new Date(inputDate);
  const year = date.getFullYear();
  const month = date.getMonth();
  const day = date.getDate();
  const formattedDate = year + "" + " " + months[month] + " " + day + "";
  return formattedDate;
}

Vue.filter('date', dateFilter)

'date'という名前で、定数'dateFilter'の値をコンポーネント側に渡します。
これでどのコンポーネントからでも使用できるようになりました。

config.jsに登録

nuxt.config.js
plugins: [
  '~/plugins/filter.js',
]

filterを適用

コンポーネント側で利用してみましょう。
'date'という名前で使用できます。
他にも書き方はありますが今回はmustache型で記述してみました。
'updateDate'はStoreで別途用意しています。

index.vue
<template>
  // {{ フィルタに渡すデータ | フィルタ }}
  <div>更新日{{ updateDate | date }}</div>
</template>

ありがとうございました。

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