首页 前端知识 element-plus el-table表格默认选中某一行

element-plus el-table表格默认选中某一行

2024-06-04 10:06:34 前端知识 前端哥 495 542 我要收藏

需求:进入页面时默认选中表格第一行 

<el-table
ref="singleTableRef"
:data="tableData"
highlight-current-row
@row-click="handleCurrentChange"
>
<el-table-column property="date" label="日期" />
<el-table-column property="name" label="姓名"/>
<el-table-column property="address" label="地址"/>
</el-table>
复制

 三个注意点:

  1. ref="singleTableRef"      ——>  用于调用 table 组件的方法 setCurrentRow(setCurrentRow 用于单选表格,设定某一行为选中行)
  2. highlight-current-row      ——>   用于高亮当前行
  3. @row-click="handleCurrentChange" ——> 当某一行被点击时会触发该事件
<script setup lang="ts">
import { firstPageAPI } from '@/utils/api'
import { ref } from 'vue'
import { ElTable } from 'element-plus'
interface User {
date: string
name: string
address: string
}
let currentRow = ref()
let tableData = ref([]) // 表格数据
const singleTableRef = ref<InstanceType<typeof ElTable>>()
//
const setCurrent = (row?: User) => {
singleTableRef.value!.setCurrentRow(row)
}
// 接口请求
await firstPageAPI().then((res: any) => {
currentRow.value = res.data[0]
tableData.value = res.data
// 选中表格第一行数据
setTimeout(() => {
setCurrent(tableData.value[0])
},200)
})
// 点击行事件
const handleCurrentChange = (val: User | undefined) => {
currentRow.value = val
console.log('选中行数据', currentRow.value)
}
onMounted(() => {
setCurrent(tableData.value[0])
})
</script>
复制

注意 在 onMounted 生命周期钩子 DOM 元素才被创建和渲染,所以 通过 ref 获取 DOM 元素时需要在 onMounted 里。

转载请注明出处或者链接地址:https://www.qianduange.cn//article/10770.html
标签
评论
发布的文章

JQuery中的load()、$

2024-05-10 08:05:15

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!