思路:需要用到ref绑定dom元素,以及dom元素的scrollTop和scrollHeight属性,最终在onUpdated函数之中让scrollTop和scrollHeight两者相等即可。
scrollTop:指的是滚动条卷去的距离(滚动条向下滚动之后距离顶部的距离)
scrollHeight:指的是内容的高度
详细代码:
<template>
<div>
<div class="container" ref="containerRef">
<template v-for="(item,index) in str" :key="index">
{{item}}<br>
</template>
</div>
</div>
</template>
<script setup>
import HelloWorld from './components/HelloWorld.vue'
import {ref,reactive,onMounted,onUpdated} from 'vue'
const containerRef = ref(null)//给div绑定ref之后,需要先定义一下,才能够使用
const str = ref(['微生岁月短,快意乘风力。'])//定义一个数组放数据,后面不断往里面放数据
onMounted(() => {
const strin = '微生岁月短,快意乘风力。'
setInterval(() => {//不断地往数组里面push数据,使div的内容不断增多
str.value.push(strin)
},200)
})
onUpdated(() => {
//在onUpdated函数里面元素变化的时候令scrollTop和scrollHeight相等,这样内容高度增加的时候
//滚动条能够向下滑动和内容高度相同的距离
containerRef.value.scrollTop = containerRef.value.scrollHeight
})
</script>
<style scoped lang="scss">
.container{
width: 400px;
height: 300px;
border: 1px solid #ccc;
/*增加滚动条*/
overflow-y:auto;
overflow-x: hidden;
&::-webkit-scrollbar {
/*滚动条整体样式*/
width: 5px;
height: 1px;
}
&::-webkit-scrollbar-thumb {
/*滚动条里面的滑块*/
border-radius: 5px;
background: #cccccc;
}
&::-webkit-scrollbar-track {
/*滚动条里面轨道背景*/
border-radius: 5px;
background: #fff;
}
}
</style>