单选:
思路:当点击的索引值 == v-for循环的索引值时,给你那个li添加选中样式
html:
1 2 3
| <ul class="box"> <li v-for="c,index of cities" :class="{checked:index==n}" @click="changeList(index)">{{c}}</li> </ul>
|
css:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <style type="text/css"> body{margin:0;} ul{ padding:0; list-style:none; margin:150px 150px; } li{ width:80px; height:50px; display:inline-block; border-radius:8px; border:1px #000 solid; text-align:center; line-height:50px; cursor:pointer; transition:all 0.3s linear; margin-left:5px; } li:hover{ background-color:#0CF; color:#fff; border:1px #fff solid; } li.checked{ background-color:#0CF; color:#fff; border:1px #fff solid; } </style>
|
js:
1 2 3 4 5 6 7 8 9 10 11 12
| var app = new Vue({ el : ".box", data : { cities : ["上海","北京","广州","重庆","西安"], n : 0 }, methods :{ changeList(index){ this.n = index; } } })
|
多选
方法一和方法二的主要的区别在于数据中有没已有标注是选中状态还是未选中状态
CSS样式如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <style type="text/css"> body{margin:0;} .box{ margin:150px 150px;} ul{ padding:0; list-style:none; } li{ width:50px; height:30px; display:inline-block; text-align:center; line-height:30px; cursor:pointer;margin-left:5px; } li:before{ display:inline-block; width:10px; height:10px; line-height:10px; content:""; border:1px #000 solid; margin-right:2px; transition:all 0.3s linear; } li.checked:before{ background-color:#0CF; border:1px #fff solid; } li.checked{color:#0CF;} </style>
|
方法一:
思路:新增一个新的空数组arr(arr的里元素的索引值表示,表示该索引值对应的li已经处于被选中状态),如果arr数组没有点击的索引值,就添加到arr数组里,如果有就把这个索引,就把这个索引从数组中删除。
html:
1 2 3
| <ul class="box"> <li v-for="c,index of cities" :class="{checked:arr.includes(index)}" @click="checkedBox(index)">{{c}}</li> </ul>
|
js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| var app = new Vue({ el : ".box", data : { cities : ["上海","北京","广州","重庆","西安"], arr : [] }, methods :{ checkedBox(i){ if(this.arr.includes(i)){ this.arr=this.arr.filter(function (ele){return ele != i;}); }else{ this.arr.push(i); } } } })
|
方法二:
思路:这个就更加通俗易懂了,把点击的那个是否选中的标志取反就可以了
html:
1 2 3 4 5
| <ul class="box"> <li v-for="c,index of cities" :class="{checked:c.bOn}" @click="checkbox(index)">{{c.city}}</li> </ul>
|
js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| var app = new Vue({ el : ".box", data : { cities : [{city:"北京",bOn:false}, {city:"上海",bOn:false}, {city:"重庆",bOn:false}, {city:"广州",bOn:false}, {city:"西安",bOn:false}] }, methods : { checkbox(i){ this.cities[i].bOn = !this.cities[i].bOn; } } })
|
转:https://blog.csdn.net/Number7421/article/details/81002729