el-table setCurrentRow会触发current-change函数 解决方案

解决el-table setCurrentRow会触发current-change函数问题

<template>
// 直接运行即可
  <template>
  <el-table
      ref="singleTableRef"
      :data="tableData"
      highlight-current-row
      style="width: 100%"
      @current-change="handleCurrentChange"
  >
    <el-table-column type="index" width="50"/>
    <el-table-column property="date" label="Date" width="120"/>
    <el-table-column property="name" label="Name" width="120"/>
    <el-table-column property="address" label="Address"/>
  </el-table>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';

const data = [
  { id: 1, date: '2016-05-03', name: 'Tom', address: 'No. 189, Grove St, Los Angeles' },
  { id: 2, date: '2016-05-02', name: 'Tom', address: 'No. 189, Grove St, Los Angeles' },
  { id: 3, date: '2016-05-04', name: 'Tom', address: 'No. 189, Grove St, Los Angeles' },
  { id: 4, date: '2016-05-01', name: 'Tom', address: 'No. 189, Grove St, Los Angeles' },
];

const singleTableRef = ref(null); // ref
const tableData = ref([]); // 表格数据
const isUpdating = ref(false); // 用于防止死循环的标识(重点)

// 高亮函数
const setCurrent = (row) => {
  if (singleTableRef.value && !isUpdating.value) {
    nextTick(() => {
      isUpdating.value = true; // 页面渲染完设置为true
      singleTableRef.value.setCurrentRow(row); // 执行高亮
      isUpdating.value = false; // 高亮之后设置为false(防止自执行current-change函数,如果不设置为false,那么就会去触发current-change函数)
    });
  }
};

const handleCurrentChange = (val) => {
  if (isUpdating.value || !val) return; // Prevent loop and handle null/undefined(防止循环和处理null/undefined)

  // Simulate async data update(模拟异步信息-)
  // setTimeout可以换做接口返回数据
  setTimeout(() => {
    const updatedData = [
      { id: 1, date: '2016-05-03', name: '小王', address: 'No. 189, Grove St, Los Angeles' },
      { id: 2, date: '2016-05-02', name: '小王', address: 'No. 189, Grove St, Los Angeles' },
      { id: 3, date: '2016-05-04', name: '小王', address: 'No. 189, Grove St, Los Angeles' },
      { id: 4, date: '2016-05-01', name: '小王', address: 'No. 189, Grove St, Los Angeles' }
    ];

    tableData.value = updatedData; // 用最新的数据或者深拷贝

    nextTick(() => {
      // find查找符合条件的
      const currentRow = updatedData.find(item => item.id === val.id);
      if (currentRow) {
        // 设置高亮
        setCurrent(currentRow);
      }
    });
  }, 1000);
};

onMounted(() => {
  // 这块设置默认选中一项
  setTimeout(() => {
    tableData.value = data;
    nextTick(() => {
      setCurrent(data[1]);
    });
  }, 800);
});
</script>


  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值