You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ag-Grid Vue中实现鼠标悬停时高亮多行?

Ag-Grid Vue 实现悬停多行高亮(当前行+上下相邻行)

完全可以实现这个需求,核心思路是通过监听行的鼠标事件记录悬停索引,再通过getRowClass动态为目标行添加高亮样式。以下是具体实现步骤:

步骤1:配置Ag-Grid并绑定事件

在模板的AgGridVue组件上绑定鼠标事件,同时指定行类名回调:

<template>
  <AgGridVue
    :columnDefs="columnDefs"
    :rowData="rowData"
    :getRowClass="getRowClass"
    @row-mouse-enter="onRowMouseEnter"
    @row-mouse-leave="onRowMouseLeave"
    <!-- 你的其他表格配置 -->
  />
</template>

步骤2:实现核心逻辑

在组件脚本中维护悬停行索引,编写事件处理和类名判断逻辑:

<script setup>
import { ref } from 'vue';
import { AgGridVue } from 'ag-grid-vue3'; // Vue2环境请使用ag-grid-vue

const hoveredRowIndex = ref(null);
const columnDefs = ref([/* 你的列定义数组 */]);
const rowData = ref([/* 你的行数据数组 */]);

const onRowMouseEnter = (params) => {
  hoveredRowIndex.value = params.node.rowIndex;
};

const onRowMouseLeave = () => {
  hoveredRowIndex.value = null;
};

const getRowClass = (params) => {
  const currentIndex = params.node.rowIndex;
  // 判断当前行是否为悬停行或其上下相邻行
  if (hoveredRowIndex.value !== null && 
      Math.abs(currentIndex - hoveredRowIndex.value) <= 1) {
    return 'highlight-row';
  }
  return '';
};
</script>

步骤3:添加高亮样式

通过样式穿透为目标行设置高亮效果:

<style scoped>
:deep(.highlight-row) {
  background-color: #e8f4fd !important; /* 自定义高亮背景色 */
}
</style>

补充说明

  • 如果表格开启了分页、排序或过滤,rowIndex是当前页面渲染的行索引,逻辑依然适用;若需要基于数据唯一标识(如ID)判断,可将hoveredRowIndex替换为数据ID,在getRowClass中对比数据ID即可。
  • 使用:deep()是为了穿透Vue的样式作用域,确保样式能作用到Ag-Grid的行元素上。

内容的提问来源于stack exchange,提问作者Liran Hersh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 09:15:34