vue 实现div上下滚动
实现 div 上下滚动的方法
使用 CSS 实现滚动
通过 CSS 的 overflow-y 属性可以轻松实现 div 的上下滚动效果。将 overflow-y 设置为 auto 或 scroll,并为 div 设置固定高度。
<template>
<div class="scroll-container">
<!-- 内容 -->
<div v-for="item in items" :key="item.id">{{ item.text }}</div>
</div>
</template>
<style>
.scroll-container {
height: 200px; /* 固定高度 */
overflow-y: auto; /* 自动显示滚动条 */
border: 1px solid #ccc; /* 可选边框 */
}
</style>
使用 Vue 动态控制滚动
如果需要通过按钮或其他交互控制滚动,可以使用 Vue 的 ref 和 DOM 操作。

<template>
<div>
<div ref="scrollContainer" class="scroll-container">
<div v-for="item in items" :key="item.id">{{ item.text }}</div>
</div>
<button @click="scrollToTop">滚动到顶部</button>
<button @click="scrollToBottom">滚动到底部</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: '内容1' },
{ id: 2, text: '内容2' },
// 更多内容...
]
};
},
methods: {
scrollToTop() {
this.$refs.scrollContainer.scrollTop = 0;
},
scrollToBottom() {
const container = this.$refs.scrollContainer;
container.scrollTop = container.scrollHeight;
}
}
};
</script>
<style>
.scroll-container {
height: 200px;
overflow-y: auto;
border: 1px solid #ccc;
}
</style>
平滑滚动效果
通过 CSS 的 scroll-behavior 属性可以实现平滑滚动效果。
<template>
<div class="smooth-scroll-container" ref="scrollContainer">
<div v-for="item in items" :key="item.id">{{ item.text }}</div>
</div>
</template>
<style>
.smooth-scroll-container {
height: 200px;
overflow-y: auto;
scroll-behavior: smooth; /* 平滑滚动 */
}
</style>
使用第三方库
如果需要更复杂的滚动功能(如无限滚动),可以使用第三方库如 vue-infinite-scroll。

安装库:
npm install vue-infinite-scroll
使用示例:
<template>
<div
v-infinite-scroll="loadMore"
infinite-scroll-disabled="busy"
infinite-scroll-distance="10"
class="scroll-container"
>
<div v-for="item in items" :key="item.id">{{ item.text }}</div>
</div>
</template>
<script>
import infiniteScroll from 'vue-infinite-scroll';
export default {
directives: { infiniteScroll },
data() {
return {
items: [],
busy: false,
page: 1
};
},
methods: {
loadMore() {
this.busy = true;
// 模拟异步加载数据
setTimeout(() => {
for (let i = 0; i < 10; i++) {
this.items.push({ id: this.page * 10 + i, text: `内容 ${this.page * 10 + i}` });
}
this.page++;
this.busy = false;
}, 1000);
}
}
};
</script>
<style>
.scroll-container {
height: 300px;
overflow-y: auto;
}
</style>
以上方法可以根据需求选择适合的方式实现 div 的上下滚动效果。






