javascript
复制代码
<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>