Vue2+ElementUI el-table初始化时定位并高亮指定行

1,068 阅读1分钟

需求描述

项目里遇到了这样一个需求: 从指定项跳转到审核页时,需要在待审核列表里高亮显示所选项,若该项在列表可视区域之外,还需要将列表滚动至该项出现在可视区域内

预期效果

image.png

image.png

实现

<el-table
        ref="couseList"
        :data="showList"
        style="width: 100%; font-size: 12px;"
        height="98%"
        highlight-current-row
        @current-change="handleChooseRow">
    <el-table-column>
    ...
    </el-table-column>
</el-table>    

js部分:

export default{
    data(){
        return{
                examinedCourseId: null,
                showList: [],
                textList: [
                {
                    id: 0,
                    name: "xxx"
                },
                //...
            ]
        }
    },
    mounted(){
        if(typeof(this.$route.params.id)=='undefined'){
            // ...
        }else{
            this.examinedCourseId = this.$route.params.id
            console.log(this.editedCourseId)
            this.getList(this.examinedCourseId).then((res)=>{
                if (res) {
                    // 模拟审核
                    this.scrollToGoalRow(12)      
                }
            })
        }
        this.showList = this.testList
    },
    methods: {
        getList(id){
            // 模拟从后端获取数据
            return new Promise((resolve, reject) => {
                setTimeout(()=>{
                    resolve(true)
                }, 200)
            })
        },
        handleChooseRow(currentRow, oldCurrentRow){
            this.examinedCourseId = currentRow.id
        },
        srollToGoalRow(id){
            let index = this.testList.findIndex((item) => item.id == id)
            let courseListEL = this.$refs.couseList.$el
            
            if(courseListEL){
                const goalRowTop = courseListEL.getElementsByClassName("el-table__row")[index].getBoundingClientRect().top
                const listTop = courseListEL.querySelector('.el-table__body').getBoundingClientRect().top
                
                if(goalRowTop - listTop - 483 > 0){
                    this.$refs.couseList.setCurrentRow(this.$refs.couseList.data[index])
                    this.$refs.couseList.$refs.bodyWrapper.scrollTop = goalRowTop - listTop
                }
            }
        }
    }
}

高亮样式

::v-deep{
    .el-table{
        .el-table__body tr.current-row>td{
            background: #6785f1bf !important;
            color: white;
            font-weight: 600;
        }
    }
}