可以结合使用Vue的ref和scrollIntoView()方法来实现
html
<template>
<div>
<button @click="addDiv">添加新的<div>标签</button>
<div ref="container" class="container">
<div v-for="(item,index) in divs" :key="index" ref="divElement" class="div-element">
<!-- 此处为动态添加的div内容 -->
</div>
</div>
</div>
</template>
javascript
<script>
export default {
data() {
return {
divs: []
};
},
methods: {
addDiv() {
this.divs.push({name:'小明'})
this.$nextTick(() => {
const divElement = this.$refs.divElement[this.$refs.divElement.length - 1];
//this.$refs.divElement.length - 1 取的是该数组中的最后一个
if (divElement) {
divElement.scrollIntoView({ behavior: 'smooth', block: 'end' });
}
});
}
}
};
</script>