期限が10日以内の値を赤く表示する [Vue.js]
はじめに
朝4時近くにこんなツイートした自分
一部だけにcss判定かけるの結構めんどくさい。
— kmmk@この1ヶ月乗り切るマン (@kami_tsukai) September 22, 2019
やり方がわからぬ。
とりあえず書いてみる
最初のやり方は、if文の際に毎回、today.setDate(today.getDate() + 10)
を書いてしまい、ループするたびに現在日時が増えて差異が生じた。
最初に現在日時の+10日の値を定義しておいてそれと比較するようにした。
isDeadLine
のture or falseでcssをつけようとしていた
html
<span v-bind:class="{'style':isDeadLine}">{{item.created_at}}</span>
script
data:function() { return { showModal: false, qiitaPosts:[], isDeadLine:false } }, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //今日から10日後の日付 const today = new Date() today.setDate(today.getDate() + 10) for(const item of this.qiitaPosts){ if(new Date(item.created_at) <= today){ this.isDeadLine = true } }
span.style{ color:red }
はじめにこのコードで試すと、CSSが全要素に反映されてしまう。
1つ条件に引っかかれば、全部のリストが赤く染まることになる。。。。。。
改善
改善した点は
- 複数のレイアウトにCSSが反映されたい→配列を作成
- 配列に値が入ってる = レイアウトを変更(includesで探す)
- 的中すると、styleクラスのレイアウトが反映されて赤く色がつく
html
<ul> <li v-for="(item,index) in array" :key="index"> <span class=”dan2″ v-bind:class="{'style':selectedItem.includes(item.id)}">{{item.created_at}}</span> </li> </ul>
script
qiitaPosts:[], //api_box selectedItem:[] //specific_css_box ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ this.selectedItem = []; //初期化 for(const item of this.qiitaPosts){ if(new Date(item.created_at) <= today){ this.selectedItem.push(item.id) } }
まとめ
複数の要素にCSSを反映させたい場合は、配列にユニークな値をいれて判定させるのがいいと思った。