環境
Vue:2.6.11
内容
Vue.jsのフイルターという機能を使うことで、画面に表示されるテキストを自由にフォーマットすることができます。
ローカルフィルター
<template> <table> <p {{sample | lowerCase}} </p> </table> </template> <script> export default { data() { return { // この文字列を小文字化する sample:"VUESAMPLE" } }, // フィルター filters:{ lowerCase(value){ return value.toLowerCase(); } }, } </script>
ローカルコンポーネント内でフィルターを実装したい場合、<script>内で filters: { } と記述し、中に関数を記述してフォーマット処理をreturnすることでフィルターを実装することができます。
上記のケースではJSのライブラリ「toLowerCase」を使って、対象となる値を小文字に変換するフィルターを作ってます。
templeteでは{{}}で値の右隣にパイプ記号を書き、そのまた右隣にフィルターを書くことで適用させます。{{sample | lowerCase}}
VUESAMPLEを小文字変換できました
グローバルフィルター
import Vue from "vue"; import "@babel/polyfill"; import App from "./App.vue"; import router from "./router"; import store from "./store"; require("./assets/scss/app.css"); Vue.config.productionTip = true; import "./global_config"; // フィルター Vue.filter("lowerCase", function(value){ return value.toLowerCase(); } new Vue({ router, store, render: h => h(App) }).$mount("#app");
12~14行目でフィルターを実装しています。
Vue.filterの1つ目の引数にフィルター名を記述し、2つ目の引数に関数でフィルターの処理を記述します。
computedとの違いについて
computedでも同じような処理を実装することができます。
ではフィルターとの違いは何でしょうか。computedの場合は1つのdataにしか処理が適用できません。
例を示します。
<template> <table> <p {{lowerCase}} </p> </table> </template> <script> export default { data() { return { sample:"VUESAMPLE" } }, computed:{ lowerCase(){ return this.sample.toLowerCase(); } }, } </script>
filterをcomputedで書き換えましたが同じように小文字変換ができています。
しかしdataのsample以外も小文字変換をしたい場合、computedだとその分処理を記述しなければなりません。
<template> <table> <p {{lowerCase}} {{lowerCase2}} </p> </table> </template> <script> export default { data() { return { sample:"VUESAMPLE", sample2:"TEST" } }, computed:{ lowerCase(){ return this.sample.toLowerCase(); }, lowerCase2(){ return this.sample2.toLowerCase(); } }, } </script>
上記のようにsample2のためにcomputedの処理を増やす必要があります。なぜならcomputedは引数がとれないため、1つのcomputedで複数のdataに適用できないためです。
一方フィルターですと、{{sample2 | lowerCase}} と対象の値にフィルターを適用させるだけでよいので処理の記述は1つだけで済みます。