web-新增数据后列表无法滚动到最底部

181 阅读1分钟

旧数据可以滚动到底部,但新增数据后调用滚动API scrollTo 无法滚动到最底部。这是因为最新一条数据还没有渲染到dom里就执行了滚动函数,所以调用dom滚动api是无法滚动到最新一条新增数据,这时候需要将滚动事件放在nextTick回调函数里执行。

nextTick所指定的回调函数会在浏览器更新DOM完毕后再执行

PS:也可使用setTimeout,效果没nextTick丝滑

<template>

<div>list列表自动滚动到底部</div>

<button @click="toScroll">滚动</button>

<div class="list" ref="listRef">

<div class="item" v-for="(item, index) in state.list" :key="index">

{{ item.title }}

</div>

</div>

</template>

  


<script setup>

import { nextTick, onMounted, reactive, ref } from "vue";

const state = reactive({

list: [],

});

const listRef = ref();

function toScroll() {

state.list.push({ title: "hehe" });

nextTick(() => {

listRef.value.scrollTo({

top: listRef.value.scrollHeight,

behavior: "smooth",

});

});

}

onMounted(() => {

let arr = [];

for (let i = 0; i < 10; i++) {

arr.push({ title: "item" + i, id: i });

}

state.list = arr;

});

</script>