html 页面
<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>
//定义变量
data () {
return {
my_stars:[],//星级OPTION
stars:[
{number:"1",value:"一级"},
{number:"2",value:"二级"},
{number:"3",value:"三级"}
],//选中的星级
}
},
js 在watch 监控 my_stars 变量
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);
});
}
}
},