Vue的单选/多选效果
includes()方法判断是否包含某一元素,返回true或false表示是否包含元素,对NaN一样有效
filter()方法用于把Array的某些元素过滤掉,filter()把传入的函数依次作用于每个元素,然后根据返回值是true还是false决定保留还是丢弃该元素:生成新的数组
一、单选
DOM文档中结构如下:
<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>
JavaScript样式如下:
<script src="vue.js"></script><script>
var app = new Vue({
el : ".box",
data : {
cities : ["上海","北京","广州","重庆","西安"],
n : 0
},
methods :{
changeList(index){
this.n = index;//this指向app
}
}
})
</script>
实现效果图:
选中效果图:
二、多选
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>
方法一:
DOM文档中结构如下:
<ul class="box"><li v-for="c,index of cities" :class="{checked:arr.includes(index)}" @click="checkedBox(index)">{{c}}</li>
</ul>
JavaScript样式如下:
<script src="vue.js"></script><script>
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;});
//this.arr=this.arr.filter((ele)=>ele!=i);
//filter()为假时删除
}else{
this.arr.push(i);
}
}
}
})
方法二:
DOM文档中结构如下:
<ul class="box"><li v-for="c,index of cities"
:class="{checked:c.bOn}"
@click="checkbox(index)">{{c.city}}</li>
</ul>
JavaScript样式如下:
<script src="vue.js"></script><script>
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
以上是 Vue的单选/多选效果 的全部内容, 来源链接: utcz.com/z/379474.html