Vue indexOf
文章描述:
indexOf查找数组中指定值,如果值不存在侧向数组里面添加,如果存在删除指定值
html
<template>
<div class="container">
<div class="list">
<div v-for="(item,index) in list" :key="index" class="item" @click="check(item)">
{{item.name}}
</div>
</div>
<div>
<div v-for="(item,index) in checkedListx" :key="i">
{{item}}
</div>
</div>
</div>
</template>
script
查找数组中是否存在id值,如果不存在侧添加,如果存在删除
export default{
data(){
return{
list:[
{region_id:1, name:'苹果'},
{region_id:2, name:'香蕉'},
{region_id:3, name:'草莓'}
],
checkedListx:[]
}
},
methods:{
check(value){
if(this.checkedListx.indexOf(value.region_id) === -1){
this.checkedListx.push(value.region_id)
}else{
this.checkedListx.splice(this.checkedListx.indexOf(value.region_id),1)
}
console.log(this.checkedListx)
}
}
}
forEach嵌套forEach
<template>
<div class="container">
<div class="list">
<div v-for="(item,index) in listx" :key="index" class="item" >
<h4>{{item.name}}</h4>
<div class="listx">
<div v-for="(itemx,i) in item.list" class="itemx" :class="itemx.cur ? 'cur': '' ">
{{itemx.title}}
</div>
</div>
</div>
</div>
</div>
</template>
script
export default{
data(){
return{
listx:[
{id:1, name:'兔崽子', likes:'1,3,5'},
{id:2, name:'小坏蛋', likes:'2,6'}
],
items:[
{id:1, title:'看电影'},
{id:2, title:'看书'},
{id:3, title:'打游戏'},
{id:4, title:'爬山'},
{id:5, title:'游泳'},
{id:6, title:'打麻将'}
]
}
},
created() {
this.list()
},
methods:{
list(){
const items = this.items
const listx = this.listx
listx.forEach((item,index)=>{
item.listArr = item.likes.split(',')
item.list = []
items.forEach((itemx,indexx)=>{
if(item.listArr.indexOf(itemx.id.toString()) === -1){
item.list.push({id: itemx.id, title: itemx.title, cur:false})
}else{
item.list.push({id: itemx.id, title: itemx.title, cur:true })
}
})
})
console.log(listx)
this.listx = listx
}
}
}
style
.list{
.item{
margin: 0 5px;
}
.item.cur{
color: rgb(66, 185, 131);
}
.listx{
display: flex;
.itemx{
margin-right: 10px;
}
.itemx.cur{
color: aqua;
}
}
}
发布时间:2023/06/06
发表评论