vue项目中,模拟多选框选中效果,点击选中再次点击取消选中

点击选中再次点击取消选中,并且不影响其他选项的选中效果。

1、在data中创建 selectArr : [ ]   数组  “selectColor”是选中后的文字样式

<li v-for="(item,index) in reasons" :key="index">

    <div @click="selectReason(item,index)" :class="selectArr .indexOf(index) != -1?'selectColor':''">

         <img v-if="selectArr .indexOf(index) != -1" src="checked.png" alt="">

         <img v-else src="check.png" alt="">

         {
   
   { item }}

    </div>

</li>

2、使用selectArr 查询数据reasons的索引是否存在,如果不存在添加在selectArr数组中,

如果已经存在了就说明当前选项是已经被选中了,就从数组中删去。

因此就达到了变成取消选中的效果了。

selectReason(item,index){

    let indexItem = this.selectArr .indexOf(index);

    if( indexItem == -1 ){

          this.selectArr .push(index);

     }else{

         this.selectArr .splice(indexItem,1);

    }
}

猜你喜欢

转载自blog.csdn.net/a_grain_of_wheat/article/details/93159391