<template>
<div class="box">
<!-- 最外层滚动容器 -->
<div class="scrollBox" ref="wrapperRef">
<!-- 包裹所有进行滚动的元素的容器 -->
<div class="scrollContent" ref="scorllContentRef">
<div
v-for="(item, index) in infoList"
:key="index"
class="showItem animate__animated animate__slideInUp"
>
{{ item.name }}--{{item.counter}}
</div>
</div>
</div>
<button @click="addAnimals">点我增加小动物</button>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
infoList: [
{
name: "章鱼哥",
age: 5,
counter: 1,
},
{
name: "派大星",
age: 3,
counter: 2,
},
],
differentCounter:3,
//保存最外层容器的dom元素
wrapperDom: "",
//保存滚动区域dom元素
scrollContentDom: "",
//保存最外层容器的offsettop
wrapperHeight: "",
};
},
mounted() {
//挂载之后获取值
//获取设置了滚动属性的dom元素
this.wrapperDom = this.$refs.wrapperRef;
//获取包裹元素的滚动区域dom
this.scrollContentDom = this.$refs.scorllContentRef;
//获取设置了滚动属性的dom元素高度
this.wrapperHeight = this.wrapperDom.offsetHeight;
},
methods: {
addAnimals() {
let obj = {
name: "海绵宝宝",
age: 1,
counter:this.differentCounter++
};
this.infoList.push(obj);
this.$nextTick(() => {
this.scrollCode();
});
},
//抽取的关于滚动的代码
scrollCode() {
//在往list中增加内容时,产生滚动效果
//获取当前滚动区域的高度
const scrollHeight = this.scrollContentDom.offsetHeight;
//获取当前滚动区域的高度和容器高度差值
const diff = scrollHeight - this.wrapperHeight;
//获取滚动区域的滚动高度
const top = this.wrapperDom.scrollTop;
if (diff - top > -65 || diff - top == 65) {
this.wrapperDom.scrollTo({
top: diff + 15,
left: 0,
behavior: "smooth",
});
console.log("------------该滚动啦");
}
},
},
};
</script>
<style scoped>
.box {
height: 100%;
width: 100%;
background: yellow;
}
.scrollBox {
height: 200px;
width: 200px;
background-color: pink;
overflow-y: scroll;
}
.showItem {
height: 30px;
width: 100%;
background: lightblue;
border-radius: 10px;
margin-bottom: 5px;
display: flex;
justify-content: center;
align-items: center;
}
.scrollContent {
background: red;
}
</style>