0
3

More than 1 year has passed since last update.

V-forで特定の要素だけclassをつける

Last updated at Posted at 2020-12-22

##やりたいこと
DBからひっぱってきたデータをvueのコンポーネントの中のdataにセットし、それをv-forで表示させているとします。
DBからひっぱってきたデータのいずれかに真偽値を設定するなどしておけばv-forの中で動きの変化はつけることができますが、
「そのコンポーネントの中だけのdataを追加し、v-forの中の特定のコンテンツだけclassをつける」などの変化をつけたい場合にやる方法。

##記述内容


//描写部分

<template>
 <div>
  <div v-for="task in tasks" :key="task.id">
   <div class="task__title">{{task.title}}</div>
  //例えばこのtask.bodyだけ、条件に応じてis-activeclassをつけたい場合
   <div class="task__body" v-bind:class="{'is-active':active === task}" >{{task.body}}
 </div>
 <button v-on:click="addActive(task)">bodyにclassをつける</button>

 </div>
</template>


<script>
export default {
 data(){
         return{
                tasks:[ ],//この中にdbからひっぱってきたデータが入っている
                active:null   
            }
        },
 methods:{
          addActive(task){
           if(this.active === task){
             this.active = null;
           }else{
            this.active = task;
           }
          }
        }
}
</script>

こんな感じで、v-forの中の値(task)を引数として渡すことで、そのactiveをtaskにすることができる。
これにより特定のtaskだけにclassを適用できる。

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