在 el-table 中筛选数据并将数据 放在表格顶部

210 阅读2分钟

在 el-table 中筛选数据并将特定 IP 地址的数据(例如 1.1.1.1 或 1.1.1.2)放在表格顶部并更改底色,可以通过以下步骤实现:

  1. 准备数据:假设你有一个数据数组 tableData
  2. 排序数据:根据 IP 地址对数据进行排序,将特定 IP 地址的数据放在前面。
  3. 自定义行样式:使用 row-class-name 属性来根据条件应用不同的样式。

以下是一个完整的示例:

<template>  
  <div>  
    <el-table  
      :data="sortedData"  
      :row-class-name="tableRowClassName"  
      style="width: 100%">  
      <el-table-column  
        prop="ip"  
        label="IP 地址"  
        width="180">  
      </el-table-column>  
      <el-table-column  
        prop="name"  
        label="名称"  
        width="180">  
      </el-table-column>  
      <!-- 其他列 -->  
    </el-table>  
  </div>  
</template>  
  
<script>  
export default {  
  data() {  
    return {  
      tableData: [  
        { ip: '1.1.1.1', name: 'Item 1' },  
        { ip: '1.1.1.2', name: 'Item 2' },  
        { ip: '192.168.1.1', name: 'Item 3' },  
        { ip: '1.1.1.1', name: 'Item 4' },  
        { ip: '1.1.1.3', name: 'Item 5' },  
      ],  
      targetIp: '1.1.1.1', // 你可以根据需要更改这个值  
    };  
  },  
  computed: {  
    sortedData() {  
      const targetIp = this.targetIp;  
      return [...this.tableData].sort((a, b) => {  
        if (a.ip === targetIp) return -1;  
        if (b.ip === targetIp) return 1;  
        return 0;  
      });  
    },  
  },  
  methods: {  
    tableRowClassName({ row }) {  
      const targetIp = this.targetIp;  
      return row.ip === targetIp ? 'blue-row' : '';  
    },  
    changeTargetIp(newIp) {  
      this.targetIp = newIp;  
    },  
  },  
};  
</script>  
  
<style>  
.blue-row {  
  background-color: blue !important;  
  color: white; /* 可选:设置文本颜色为白色以便在蓝色背景上可读 */  
}  
</style>

解释

  1. 数据准备tableData 是你表格的原始数据。

  2. 排序数据

    • 使用 computed 属性 sortedData 对数据进行排序。
    • 排序逻辑是将 targetIp 对应的行放在前面,其他行保持原顺序。
  3. 自定义行样式

    • 使用 row-class-name 属性,并定义一个方法 tableRowClassName 来根据条件返回类名。
    • 如果 row.ip 等于 targetIp,则返回 'blue-row' 类名。
  4. 样式定义

    • 在 <style> 标签中定义 .blue-row 类,设置背景颜色为蓝色。

动态更改目标 IP

如果你希望动态更改目标 IP(例如,从 1.1.1.1 切换到 1.1.1.2),可以添加一个方法 changeTargetIp,并在需要时调用它:

<template>  
  <div>  
    <el-button @click="changeTargetIp('1.1.1.2')">切换到 1.1.1.2</el-button>  
    <el-table  
      :data="sortedData"  
      :row-class-name="tableRowClassName"  
      style="width: 100%">  
      <!-- 表格列 -->  
    </el-table>  
  </div>  
</template>

通过这种方式,你可以轻松地在表格中筛选和排序数据,并动态更改特定行的样式。