在el-table中,如何实现hover单元格时添加class,移出时消失?

856 阅读2分钟

在 Vue 的 Element UI 库中,el-table 组件并没有直接提供类似于鼠标悬停(hover)时给单元格内元素增加类名的内置功能。但是,你可以通过结合 CSS 和 Vue 的事件监听来实现这个需求。

以下是一种可能的实现方法:

  1. 使用 Vue 的事件监听:在 el-table-column 中使用 cell-mouse-enter 和 cell-mouse-leave 事件来监听鼠标的进入和离开。
  2. 修改元素的类名:在事件处理函数中,你可以通过修改单元格内元素的类名来实现样式的变化。这通常涉及到对 DOM 的直接操作,但在 Vue 中,我们更推荐使用数据驱动的方式。你可以使用 Vue 的 ref 或者其他方式来标识和访问 DOM 元素。

然而,直接操作 DOM 元素并不是 Vue 的最佳实践。因此,一种更优雅的方式是使用 Vue 的动态类名绑定。你可以在单元格的模板中使用 :class 指令来根据某个数据属性动态地添加或删除类名。

下面是一个简化的示例代码:

<template>
  <el-table
    :data="tableData"
    style="width: 100%"
    :cell-class-name="cellClassName"
    @cell-mouse-enter="handleCellMouseEnter"
    @cell-mouse-leave="handleCellMouseLeave"
  >
    <el-table-column prop="date" label="日期" width="180">
      <template slot-scope="scope">
        <div class="cell-content" :class="scope.row.hoverClass">
          <!-- 其他内容 -->
        </div>
      </template>
    </el-table-column>
    <!-- 其他列 -->
  </el-table>
</template>

  
<script>  
export default {  
  data() {  
    return {  
      tableData: [/* ...你的数据... */],  
      hoveredRow: null, // 用于记录当前悬停的行的索引或唯一标识  
    };  
  },  
  methods: {  
    handleCellMouseEnter(row, column, cell, event) {  
      // 根据你的需要设置 hoveredRow,例如 row.id 或 row 的索引  
      this.hoveredRow = row.id;  
    },  
    handleCellMouseLeave(row, column, cell, event) {  
      // 清除 hoveredRow  
      this.hoveredRow = null;  
    },  
    cellClassName({ row, rowIndex, column, columnIndex }) {  
      // 根据 hoveredRow 判断是否添加类名  
      if (this.hoveredRow === row.id) {  
        return 'cell-hovered'; // 返回要添加的类名  
      }  
      return ''; // 否则不添加类名  
    },  
  },  
};  
</script>  
  
<style scoped>  
.cell-hovered .cell-content {  
  /* 你的悬停样式 */  
}  
</style>

注意:在这个示例中,我使用了 hoveredRow 来跟踪当前悬停的行的标识(例如,行的 ID)。然后,在 cellClassName 方法中,我根据 hoveredRow 的值来决定是否给单元格添加类名。当然,你可以根据你的具体需求来调整这个逻辑。另外,请注意在 cell-class-name 中,我只是返回了一个固定的类名 'cell-hovered',但你也可以返回一个更复杂的逻辑,根据单元格的具体内容或其他因素来动态地生成类名。