vue 实现数据滚动
实现数据滚动的 Vue 方法
使用 CSS 实现滚动
通过 CSS 的 overflow 和 scroll 属性实现简单滚动:
<template>
<div class="scroll-container">
<div v-for="item in items" :key="item.id">{{ item.text }}</div>
</div>
</template>
<style>
.scroll-container {
height: 300px;
overflow-y: scroll;
border: 1px solid #ccc;
}
</style>
使用第三方库(如 vue-seamless-scroll)
安装 vue-seamless-scroll 库:
npm install vue-seamless-scroll
在组件中使用:
<template>
<vue-seamless-scroll :data="items" class="scroll-wrapper">
<div v-for="item in items" :key="item.id">{{ item.text }}</div>
</vue-seamless-scroll>
</template>
<script>
import vueSeamlessScroll from 'vue-seamless-scroll'
export default {
components: { vueSeamlessScroll },
data() {
return {
items: [...]
}
}
}
</script>
<style>
.scroll-wrapper {
height: 300px;
overflow: hidden;
}
</style>
自定义指令实现自动滚动
创建自定义指令实现自动滚动效果:
Vue.directive('auto-scroll', {
inserted(el, binding) {
const speed = binding.value || 1
let scrollTop = 0
const scrollHeight = el.scrollHeight
const clientHeight = el.clientHeight
function scroll() {
scrollTop += speed
if (scrollTop >= scrollHeight - clientHeight) {
scrollTop = 0
}
el.scrollTop = scrollTop
requestAnimationFrame(scroll)
}
requestAnimationFrame(scroll)
}
})
使用指令:
<template>
<div v-auto-scroll="2" class="scroll-box">
<div v-for="item in items" :key="item.id">{{ item.text }}</div>
</div>
</template>
<style>
.scroll-box {
height: 300px;
overflow: hidden;
}
</style>
响应式滚动容器
动态计算容器高度并实现响应式滚动:
<template>
<div ref="scrollContainer" class="responsive-scroll">
<div v-for="item in items" :key="item.id" class="scroll-item">
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [...],
containerHeight: 0
}
},
mounted() {
this.calculateHeight()
window.addEventListener('resize', this.calculateHeight)
},
beforeDestroy() {
window.removeEventListener('resize', this.calculateHeight)
},
methods: {
calculateHeight() {
this.containerHeight = window.innerHeight * 0.6
}
}
}
</script>
<style>
.responsive-scroll {
overflow-y: auto;
}
.scroll-item {
padding: 10px;
border-bottom: 1px solid #eee;
}
</style>
虚拟滚动优化(vue-virtual-scroller)
对于大数据量场景,使用虚拟滚动优化性能:
npm install vue-virtual-scroller
实现方式:

<template>
<RecycleScroller
class="scroller"
:items="items"
:item-size="50"
key-field="id"
>
<template v-slot="{ item }">
<div class="item">{{ item.text }}</div>
</template>
</RecycleScroller>
</template>
<script>
import { RecycleScroller } from 'vue-virtual-scroller'
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css'
export default {
components: {
RecycleScroller
},
data() {
return {
items: [...]
}
}
}
</script>
<style>
.scroller {
height: 500px;
}
.item {
height: 50px;
padding: 10px;
}
</style>






