vue3 el-table手动选中某一行、设置默认选中某一行
warning:
这篇文章距离上次修改已过204天,其中的内容可能已经有所变动。
在Vue 3中,使用Element Plus(假设你正在使用Element UI)的el-table
组件,你可以通过ref
属性和组件的highlight-current-row
属性来手动选中表格的某一行,并通过row-class-name
属性来设置默认选中的行。
以下是如何实现这两个需求的示例代码:
<template>
<el-table
:data="tableData"
ref="myTable"
highlight-current-row
style="width: 100%"
@current-change="handleCurrentChange"
>
<el-table-column prop="date" label="日期" width="180"></el-table-column>
<el-table-column prop="name" label="姓名" width="180"></el-table-column>
<el-table-column prop="address" label="地址"></el-table-column>
</el-table>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { ElTable, ElTableColumn } from 'element-plus';
const tableData = ref([
{ date: '2016-05-02', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄' },
// ...更多数据
]);
// 手动选中某一行
function selectRow(row) {
const table = this.$refs.myTable;
table.setCurrentRow(row);
}
// 设置默认选中行的回调
function handleCurrentChange(currentRow, oldCurrentRow) {
console.log('当前行数据:', currentRow);
console.log('之前行数据:', oldCurrentRow);
}
onMounted(() => {
// 设置默认选中第一行
selectRow(tableData.value[0]);
});
</script>
在这个示例中,highlight-current-row
属性使表格行在hover时高亮显示。ref="myTable"
允许你通过this.$refs.myTable
访问表格实例。@current-change
事件用于监听当前行变化。selectRow
函数通过setCurrentRow
方法手动设置选中的行。onMounted
钩子在组件挂载完成后自动执行,并通过selectRow
函数选择了默认的行数据。
请确保你已经安装了Element Plus,并在你的Vue 3项目中正确地引入了Element Plus组件。
评论已关闭