elementui 表格应用1:多选+搜索框+保持选中状态
场景:
一个带多选、关键字搜索功能的表格。要求在以下情形下, 保持数据项选中状态的一致:
1、有、无关键字;
2、数据项选中状态进行切换;
具体如下图:
案例代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="//unpkg.com/vue/dist/vue.js"></script> <script src="//unpkg.com/element-ui@2.13.0/lib/index.js"></script> <link href="//unpkg.com/element-ui@2.13.0/lib/theme-chalk/index.css" rel="stylesheet"> </head> <body> <div id="app"> <template> <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange1"> <el-table-column type="selection" width="55"> </el-table-column> <el-table-column label="日期" width="120"> <template slot-scope="scope">{{ scope.row.date }}</template> </el-table-column> <el-table-column prop="name" label="姓名" width="120"> </el-table-column> <el-table-column align="right"> <template slot="header" slot-scope="scope"> <el-input @input="searchChange1" v-model="search" size="mini" placeholder="输入关键字搜索"/> </template> <template slot-scope="scope"> <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">Edit </el-button> <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">Delete </el-button> </template> </el-table-column> </el-table> </template> </div> <script> var Main = { data() { return { search: '', searchFlag: false, tableData: [], originArr: [{ date: '2016-05-03', name: '1', }, { date: '2016-05-02', name: '2', }, { date: '2016-05-04', name: '3', }, { date: '2016-05-01', name: '4', }, { date: '2016-05-08', name: '5', }, { date: '2016-05-06', name: '6', }, { date: '2016-05-07', name: '王小虎', }], multipleSelection: [] } }, created() { this.tableData = [...this.originArr]; // 保持源数组的独立性, }, methods: { handleSelectionChange1(val) { console.log('改变:', this.searchFlag) console.log(this.tableData) console.log(this.originArr) if (this.searchFlag) { // 手动选中过程中不予响应 return; } this.tableData.forEach(item => { item.checked = false; }) val.forEach(row => { row.checked = true; }) }, searchChange1() { var arr = this.originArr.filter(data => !this.search || data.name.toLowerCase().includes(this.search.toLowerCase())); this.tableData.splice(0,this.tableData.length); Array.prototype.push.apply(this.tableData, arr); // 不改变tableData 数组的引用地址。保持其响应式。 this.$nextTick(() => { this.searchFlag = true // 手动选中前 禁止多选事件响应 this.tableData.forEach(item => { if (item.checked) this.$refs.multipleTable.toggleRowSelection(item, true); }) this.searchFlag = false; // 放开多选事件响应 }) } } } var Ctor = Vue.extend(Main) new Ctor().$mount('#app') </script> </body> </html>
关键解读:
1、对数组项 使用 check属性 来标识是否被选中;
2、多选事件里,保证选中项 被正确标识;
3、输入框改变事件里,进行表格数据的正确填充(保证其引用不变,否则 手动选中不起作用);在nextTick事件里,进行手动选中