html代码:
<el-form class="container">
<el-form-item label="查询年份:">
<el-select v-model="valueYears" ref="years" multiple collapse-tags placeholder="请选择" @change="changeYearsSelect">
<el-option v-for="item in searchDataObj.searchYears.data" :key="item.value" :label="item.text" :value="item.value"></el-option>
</el-select>
</el-form-item>
</el-form>
js代码:
data:
searchDataObj:{
searchYears: {
data: [{value: 'ALL_SELECT', text: '全部'},{value: '2019', text: '2019'},{value: '2018', text: '2018'}],
oldSearchJobType: [],
},
valueYears: [],
},
methods:{
init: function(){
//this.changeYearsSelect('ALL_SELECT'); //默认全选
this.valueYears.push( that.searchDataObj.searchYears.data[1].value); //默认选中第一个值
},
changeYearsSelect(val) {
this.commonChangeSelect(val, this.searchDataObj.searchYears.data, this.searchDataObj.searchYears.oldSearchJobType,'valueYears' )
},
commonChangeSelect(currentSelectVal, allOptions, oldValObj, vModelKey){
var realValues = this.$data[vModelKey];
const allValues = [];
// 保留所有值
for (const item of allOptions) {
allValues.push(item.value)
}
// 用来储存上一次的值,可以进行对比
const oldVal = oldValObj.length === 1 ? oldValObj[0] : [];
// 若是全部选择
if (currentSelectVal.includes('ALL_SELECT')) {
realValues = allValues;
}
// 取消全部选中 上次有 当前没有 表示取消全选
if (oldVal.includes('ALL_SELECT') && !currentSelectVal.includes('ALL_SELECT')) {
realValues = [];
}
// 点击非全部选中 需要排除全部选中 以及 当前点击的选项
// 新老数据都有全部选中
if (oldVal.includes('ALL_SELECT') && currentSelectVal.includes('ALL_SELECT')) {
const index = currentSelectVal.indexOf('ALL_SELECT');
currentSelectVal.splice(index, 1); // 排除全选选项
realValues = currentSelectVal;
}
// 全选未选 但是其他选项全部选上 则全选选上 上次和当前 都没有全选
if (!oldVal.includes('ALL_SELECT') && !currentSelectVal.includes('ALL_SELECT')) {
if (currentSelectVal.length === allValues.length - 1){
realValues = ['ALL_SELECT'].concat(currentSelectVal);
}
}
// 储存当前最后的结果 作为下次的老数据
oldValObj[0] = realValues;
this.$set(this, vModelKey, realValues);
},
},
mounted: function() {
this.init();
}
参考网址:https://www.cnblogs.com/sinosaurus/p/9047395.html