Vue使用vue-multiselect筛选无选中项时显示全部表格数据的实现问题
实现方案
你只需要新增计算属性做动态筛选,调整少量代码即可实现需求,核心逻辑是:每个筛选维度如果未选中任何值,就默认该维度全部匹配,不做过滤限制。
步骤1:在Vue实例中新增计算属性
和methods同级添加如下计算属性,用来返回动态筛选后的表格数据:
computed: { filteredWorkData() { // 先把嵌套的原始数据扁平化,方便筛选 const allRecords = [] this.workNumbers.forEach(empGroup => { Object.values(empGroup).forEach(empDateObj => { Object.values(empDateObj).forEach(record => { allRecords.push(record) }) }) }) // 筛选逻辑:每个维度为空则跳过该维度过滤 return allRecords.filter(record => { // 班次筛选 const matchShift = this.ShiftArray.length === 0 ? true : this.ShiftArray.includes(record.shift) // 区域筛选 const matchArea = this.areaArray.length === 0 ? true : this.areaArray.includes(record.area) // 门店筛选 const matchStore = this.StoreArray.length === 0 ? true : this.StoreArray.includes(record.store) // 品类筛选 const matchCategory = this.CategoryArray.length === 0 ? true : this.CategoryArray.includes(record.category) // 输出类型筛选,可根据自身业务补充判断逻辑 const matchOutput = !this.selectedOutput ? true : true return matchShift && matchArea && matchStore && matchCategory && matchOutput }) } }
步骤2:修复多选添加方法的逻辑错误
你当前的addShiftSelection方法存在逻辑问题:判断用的是fields.id,存的却是fields.name,会导致重复值无法正确识别,修改为:
addShiftSelection(){ this.selectedShift.forEach(fields => { // 把判断条件从fields.id改成fields.name if(this.ShiftArray.indexOf(fields.name) !== -1){ console.log("This exists") }else{ this.ShiftArray.push(fields.name); } }); },
步骤3:修改表格部分的渲染逻辑
把原来基于原始workNumbers的嵌套循环,改成直接遍历筛选后的计算属性即可,结构更简洁:
<table> <tbody> <tr v-for="record in filteredWorkData" :key="`${record.name}-${record.date}`"> <td v-for="date in dates" :key="date"> <div v-if="record.date === date"> @{{selectedOutput?.name === 'Purchased' ? record.purchased : record.sold}} </div> </td> </tr> </tbody> </table>
现在当所有筛选数组为空时,计算属性会直接返回全部原始数据,表格就会展示所有内容,有选中值时按选中条件过滤,符合你的需求。
内容的提问来源于stack exchange,提问作者Geoff_S
相关产品推荐
相关产品推荐

