vue实现文章滚动
Vue 实现文章滚动效果
使用 CSS 实现基础滚动
通过 CSS 的 overflow 和 height 属性控制滚动区域,适用于静态内容滚动。在 Vue 模板中定义固定高度的容器,内容超出后自动滚动。
<template>
<div class="scroll-container">
<div v-for="(item, index) in articles" :key="index" class="article-item">
{{ item.content }}
</div>
</div>
</template>
<style>
.scroll-container {
height: 300px;
overflow-y: auto;
border: 1px solid #eee;
}
.article-item {
padding: 10px;
border-bottom: 1px solid #ddd;
}
</style>
动态加载数据滚动
结合 v-for 和异步数据加载,实现滚动到底部时自动加载新内容。监听滚动事件,计算滚动位置触发加载逻辑。
<template>
<div class="dynamic-scroll" @scroll="handleScroll">
<div v-for="(item, index) in articles" :key="index">
{{ item.title }}
</div>
<div v-if="loading">加载中...</div>
</div>
</template>
<script>
export default {
data() {
return {
articles: [],
loading: false,
page: 1
};
},
methods: {
async loadArticles() {
this.loading = true;
const newArticles = await fetchArticles(this.page);
this.articles.push(...newArticles);
this.page++;
this.loading = false;
},
handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target;
if (scrollHeight - scrollTop === clientHeight) {
this.loadArticles();
}
}
},
mounted() {
this.loadArticles();
}
};
</script>
使用第三方库优化体验
对于复杂滚动需求(如虚拟滚动),可引入 vue-virtual-scroller 等库,高效渲染大量数据。
安装库:
npm install vue-virtual-scroller
示例实现:

<template>
<RecycleScroller
class="scroller"
:items="articles"
:item-size="50"
key-field="id"
>
<template v-slot="{ item }">
<div class="article">
{{ item.title }}
</div>
</template>
</RecycleScroller>
</template>
<script>
import { RecycleScroller } from 'vue-virtual-scroller';
export default {
components: { RecycleScroller },
data() {
return {
articles: [] // 长列表数据
};
}
};
</script>
<style>
.scroller {
height: 400px;
}
</style>
平滑滚动动画
通过 CSS 或 JavaScript 实现平滑滚动效果,提升用户体验。使用 scroll-behavior 或自定义动画函数。
CSS 方式:
.scroll-container {
scroll-behavior: smooth;
}
JavaScript 动画:

methods: {
scrollToTop() {
const container = this.$el.querySelector('.scroll-container');
const duration = 500;
const start = container.scrollTop;
const change = -start;
let startTime = null;
function animateScroll(currentTime) {
if (!startTime) startTime = currentTime;
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
container.scrollTop = start + change * progress;
if (progress < 1) requestAnimationFrame(animateScroll);
}
requestAnimationFrame(animateScroll);
}
}
滚动位置恢复
在 Vue Router 的路由切换中保存和恢复滚动位置,使用 keep-alive 和滚动行为配置。
路由配置示例:
const router = new VueRouter({
routes: [...],
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition;
} else {
return { x: 0, y: 0 };
}
}
});
组件内使用 keep-alive:
<keep-alive>
<router-view></router-view>
</keep-alive>






