vue标签单选、多选效果

一、页面

<van-tag type="primary" size="large" :plain="item.checked == true ? false : true"
    v-for="(item , index) in tagListType" :key="index" @click="bindTag(index)">{
   
   {item.name}}
    </van-tag>

在这里插入图片描述

二、公共数据

//初始数据
tagListType: [{
    
    
    name: "全部",
    checked: true,
    id:''
}, {
    
    
    name: "选项一",
    checked: false,
    id:1
}, {
    
    
    name: "选项二",
    checked: false,
    id:2
}],
//盛放选中标签的id
tagListTypeArr: []

三、单选

需求: 选中当前标签获取id追加到数组,只可选中其中一项

bindTag(index){
    
    
	let id= this.tagListType[index].id
	this.tagListType.map(item => {
    
    
        item.checked = false
        this.tagListType[index].checked = true
    })
    this.tagListTypeArr.splice(0, 1)
    this.tagListTypeArr.push(id)
}

四、多选

需求: 选中当前标签获取id追加到数组,可选中多个,但如果选择全部则清除其它已选择的标签

bindTag(index){
    
    
    let id = this.tagListType[index].id
    if(index == 0){
    
    
    	//选中全部标签清除其他标签
        this.tagListType.map(item => {
    
    
            item.checked = false
            this.tagListType[index].checked = true
        })
        this.tagListTypeArr = []
    }else{
    
    
    	//选中其他标签清除全部标签
        this.tagListType[0].checked = false
        //点击标签如果标签已选中则取消,未选中则选中,并把id追加到数组
        if (this.tagListTypeArr.includes(id)) {
    
    
            this.tagListType[index].checked = false
            this.tagListTypeArr.splice(this.tagListTypeArr.findIndex(item => item === id), 1)
        } else {
    
    
            this.tagListType[index].checked = true
            this.tagListTypeArr.push(id)
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37332614/article/details/130821530