最终实际效果如下:
代码如下:
<template>
<div>
<el-select v-model="my_stars" multiple collapse-tags placeholder="请选择">
<el-option label="全选" value="0" key="0"></el-option>
<el-option
v-for="item in stars"
:key="item.number"
:label="item.value"
:value="item.number"
></el-option>
</el-select>
</div>
</template>
<script>
export default {
data() {
return {
my_stars: [], //星级OPTION
stars: [
{ number: "1", value: "一级" },
{ number: "2", value: "二级" },
{ number: "3", value: "三级" },
], //选中的星级
};
},
watch: {
my_stars: function(val, oldval) {
let newindex = val.indexOf("0"),
oldindex = oldval.indexOf("0"); //获取val和oldval里all的索引,如果没有则返回-1,有则
//选择全选时,之前是没有全选状态
if (newindex != -1 && oldindex == -1 && val.length > 0) {
this.my_stars = ["0"];
this.stars.forEach((v) => {
this.my_stars.push(v.number);
});
//选择全选时,之前是全选状态
} else if (newindex == -1 && oldindex != -1 && val.length > 0) {
this.my_stars = [];
//选择 非全选 选项时,之前是全选状态
} else if (
newindex != -1 &&
oldindex != -1 &&
Math.abs(val.length - oldval.length) == 1
) {
this.my_stars.shift("0");
//选择 非全选 选项时,选择完了所有的星级级别
} else if (
newindex == -1 &&
oldindex == -1 &&
this.stars.length == val.length &&
val.length > 0
) {
this.my_stars = ["0"];
this.stars.forEach((v) => {
this.my_stars.push(v.number);
});
}
},
},
};
</script>
选项框中也可以不省略展示,如下图可以通过collapse-tags属性控制: