
默认第一个按钮自带primary属性颜色,点击其中一个按钮,切换到primary类型,而其他按钮取消该类型的样式
******** html *********
<ul class="btns">
<li v-for="(item, index) in list" :key="item.id">
<el-button size="small" @click="changeBg(item, index)" :type="item.btnType">{{ item.name }} {{ item.count }}</el-button>
</li>
</ul>
*********** js **************
list: [
{ id: 1, name: "全部证件", count: 38540, btnType: this.btnType },
{ id: 2, name: "手写识别", count: 540, btnType: this.btnType },
{ id: 3, name: "语音文字提取", count: 40, btnType: this.btnType },
],
btnType: '',
changeBg(ele, idx) {
this.list.forEach(item => {
item.btnType = ""; // 排他
if ((ele.id ==item.id)) { // 通过id进行对比,而不是通过索引值进行对比
this.list[idx].btnType = "primary"; // 修改数组中指定对象里的btnType
}
});
},
********* css ********
ul {
list-style: none;
width: 100%;
margin-bottom: 15px;
padding: 5px 0;
display: flex;
li {
margin: 0 5px 5px 0;
}
}
本文介绍了一种使用Vue实现按钮组的功能,通过点击不同按钮来切换样式并保持选中状态的方法。具体实现了当点击某个按钮时,该按钮会变为primary类型,同时取消其他按钮的primary样式。

6076

被折叠的 条评论
为什么被折叠?



