轉:https://blog.csdn.net/Number7421/article/details/81002729
不過我以前都寫過這三種方法了,很pang額,怕之后忘記了,偷個懶拿別人的,以免以后忘記了
一、單選:
思路:當點擊的索引值 == v-for循環的索引值時,給你那個li添加選中樣式
html:
<ul class="box"> <li v-for="c,index of cities" :class="{checked:index==n}" @click="changeList(index)">{{c}}</li> </ul>
CSS樣式如下:

<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:
var app = new Vue({ el : ".box", data : { cities : ["上海","北京","廣州","重慶","西安"], n : 0 }, methods :{ changeList(index){ this.n = index;//this指向app } } })
二、多選
方法一和方法二的主要的區別在於數據中有沒已有標注是選中狀態還是未選中狀態
CSS樣式如下:

<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:
<ul class="box"> <li v-for="c,index of cities" :class="{checked:arr.includes(index)}" @click="checkedBox(index)">{{c}}</li> </ul>
js:
var app = new Vue({ el : ".box", data : { cities : ["上海","北京","廣州","重慶","西安"], arr : [] }, methods :{ checkedBox(i){ if(this.arr.includes(i)){ //includes()方法判斷是否包含某一元素,返回true或false表示是否包含元素,對NaN一樣有效 //filter()方法用於把Array的某些元素過濾掉,filter()把傳入的函數依次作用於每個元素,然后根據返回值是true還是false決定保留還是丟棄該元素:生成新的數組 this.arr=this.arr.filter(function (ele){return ele != i;}); }else{ this.arr.push(i); } } } })
方法二:
思路:這個就更加通俗易懂了,把點擊的那個是否選中的標志取反就可以了
html:
<ul class="box"> <li v-for="c,index of cities" :class="{checked:c.bOn}" @click="checkbox(index)">{{c.city}}</li> </ul>
js:
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; } } })