1.setScrollTop方法

<el-table ref="tableRef" :data="accountList" max-height="560" class="mt-16 associate-table normal-size">
                <el-table-column prop="userName" label="用户名" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.userName" placeholder="请输入用户名" maxlength="50" class="input" />
                    </template>
                </el-table-column>
               <div class="btn">
                <svg-icon name="tianjia" class="icon2" @click="handleAdd" />
                <span class="font" @click="handleAdd">新增</span>
            </div>
</el-table>
<script lang="ts">
   const handleAdd = () => {
	    const newData: any = {
	        userName: "",
	    };
	    accountList.value.push(newData);
	    //超过设置的高度出现滚动条,添加行定位到底部
	    1.给table添加ref、
	    2.setScrollTop()的方法
	        setTimeout(() => {
	        //1、50为每一行的高度;2、 accountList.value.length为数据数量
	        var ScrollTop = 50 * accountList.value.length;
	        console.log(ScrollTop,'ScrollTop');
	        tableRef.value.setScrollTop(ScrollTop);
	    }, 100);
 }   
</script>

2.scrollTop,scrollTop 表示滚动的高度

<el-table :data="accountList" max-height="560" class="mt-16 associate-table normal-size">
                <el-table-column prop="userName" label="用户名" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.userName" placeholder="请输入用户名" maxlength="50" class="input" />
                    </template>
                </el-table-column>
               <div class="btn">
                <svg-icon name="tianjia" class="icon2" @click="handleAdd" />
                <span class="font" @click="handleAdd">新增</span>
            </div>
</el-table>
<script lang="ts">
 const handleAdd = () => {
	     const newData: any = {
	        userName: "",
	    };
	    accountList.value.push(newData);
	    //超过设置的高度出现滚动条,添加行定位到底部
	    1.先拿到设置table的最大高度【滚动条的高度】的元素,获取元素的clientHeight 
	    2.在拿到table的所有行的高度的元素,获取元素的clientHeight 
	    3,当他们相减就是滚动条距离底部的间距,在设置scrollTop 
	    const el: any = document.querySelector('.associate-table .el-scrollbar__wrap')
	    const el2: any = document.querySelector('.associate-table .el-table__body tbody')
	    setTimeout(() => {
	        const height = el2.clientHeight - el.clientHeight
	        if (height > 0) {
	            el.scrollTop = height
	        }
	    }, 200)
	 }

</script>

3.通过watch监听到table数据的变化,设置setScrollTop方法

watch( accountList.value, () => {
  nextTick(() => {
    tableRef.value.setScrollTop(800);
  });
});
Logo

前往低代码交流专区

更多推荐