vue.jsには便利なフィルターという機能がある。
以下のような形で書かれ、“パイプ(‘|’)” 記号を使用する
<!-- mustaches -->
{{ message | capitalize }}
<!-- v-bind -->
<div v-bind:id="rawId | formatId"></div>
コンポーネントのオプション内でローカルフィルタを定義します。
filters: {
capitalize: function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
}
}
コンポーネントをまたいでグローバルで使用する場合は、 Vue インスタンスを作成する前にグローバルでフィルタを定義することができます。頻繁に使用するものはこちらです。
Vue.filter('capitalize', function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})
new Vue({
// ...
})
よく使うフィルターまとめ
よく使うフィルターをまとめていきます。
時間に関するフィルター
UTCの日時を2019/12/30のような形に変換
Vue.filter('shapeDate', function(val){
var d = new Date(val);
var formatted = `
${d.getFullYear()}/${d.getMonth()+1}/${d.getDate()}`.replace(/\n|\r/g, '');
return formatted;
});
残り時間とか
Vue.filter('remainingTime', function(val){
var target = new Date(val);
const days = Math.floor( target.getUTCDate());
const hours = target.getUTCHours();
const minutes = target.getUTCMinutes();
const seconds = target.getUTCSeconds();
return `${days}日${hours}時間${minutes}分${seconds}秒`;
});
頻繁に使う機能が増えたら追記します。