elemntui Table实现多选+限制选择项+搜索框+保持选中状态
实现以下功能:
1、可多选
2、限制多选选项最多可以选择5项
3、有搜索框
4、搜索后选中\取消选择,保持状态
代码实现如下:
//手打的,不是从编辑器里赋值过来的,有些单词可能打错了,样式也去调了
//搜索输入栏
<div>
<input
text="text"
placeholder="请输入搜索项"
v-modle="search"
v-on:input=“searchName”
/>
</div>
//表格
<div class="table"
<el-table
ref="table"
stripe
:data="showList"
tooltip-effect="dark"
max-height="200"
@selection-change="selectionChange"
>
<el-table-column type="selection" width="55"></el-table-column>
<el-table-column type="name" label="姓名"></el-table-column>
</el-table>
</div>
//直接写涉及到的
data(){
tableDate:[],
showList:[],
selecValue:'',
searchFlag:false,
selectedList:[]
},
created(){
this.showList = [...this.tableDate]; //保持源数据的独立性
},
methods:{
selectionChange (val) {
this.selectedList = val;
if(this.searchFlag) {
return ;
}
this.showList.forEach (item => {
item.checked = false;
})
val.forEach (row => {
row.checked = true;
});
//限制选中个数
if (this.selectedList.length >= 3) {
this.selectedList = val.slice(0,3);
let tempArr = val.slice(3);
if(tempArr.length !== 0){
temArr.forEach(ele => {
this.$refs["table"].toggleRowSelection(ele,false);
this.$alert("最多只能选择3个!")
})
}
}
//如果是组件 需要将最后的选中项给到父组件
this.$emit('selectedList',this.selectedList);
},
//搜索
searchName(){
//重新记录选中项
this。selectedList = [];
var arr = this.tableDate.filter( data => !this.selecValue || data.username.toLowerCase().includes(this.selectedValue.toLowerCase()));
this.showList.splice(0,this.showList.length);
Array.prototype.push.apply(this.showList,arr);//不改变showList数组的引用
this.$nexttTick( () => {
this.searchFlag = true;//手动选中前,禁止多选事件响应
this.showList.forEach( item => {
if(item.checked){
this.refs['table'].toggleRowSelection(item,true);
}
});
this.searchFlag = false;//放开所选事件响应
this.$emit('selectedList',this.selectedList);
})
}
}