代码示例:
<script setup lang="ts">
import {nextTick, onMounted, ref} from 'vue'
const count = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
const ddd = ref(null);
nextTick(() => {
ddd.value.scrollTop = ddd.value.scrollHeight;
})
onMounted(() => {
if (ddd.value) {
nextTick();
}
})
</script>
<template>
<div style="height: 50vh; width: 300px; margin:50px auto; border: 1px solid red;overflow-y: auto;" ref="ddd">
<div v-for="i in count" style="height: 20px; width: 200px; border: 1px solid black;">
{{ i }}
</div>
</div>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>
代码说明:
1.创建了一个div,里面包含了若干个小的div,该父div支持竖轴方向的滚动
2.给父div绑定一个ref值ddd
3.在页面onMounted时,调整页面的数据显示
4.这里使用了 nextTick 方法,目的是为了确保在 Vue 完成对 DOM 的更新后执行回调,这对于处理依赖于最新 DOM 状态的操作非常重要!防止卡壳~
截图展示如下: