vue滑动元素实现滚动
实现 Vue 中滑动元素滚动的方法
使用原生滚动属性
在 Vue 模板中直接为元素添加 CSS 的 overflow 属性,结合 v-for 渲染列表数据。这种方式适合简单的滚动需求。
<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: auto;
}
</style>
使用第三方库(如 better-scroll)
对于更复杂的滚动效果(如惯性滚动、边界回弹),可以使用 better-scroll 库。需先安装依赖:

npm install better-scroll
在 Vue 组件中初始化 better-scroll:
import BScroll from 'better-scroll';
export default {
data() {
return {
items: [...], // 数据列表
scroll: null
};
},
mounted() {
this.$nextTick(() => {
this.scroll = new BScroll(this.$refs.scrollContainer, {
scrollY: true,
click: true
});
});
},
template: `
<div ref="scrollContainer" class="scroll-container">
<div class="scroll-content">
<div v-for="item in items" :key="item.id">{{ item.text }}</div>
</div>
</div>
`
};
自定义指令实现滚动
通过 Vue 自定义指令监听触摸事件,实现移动端滑动效果:

Vue.directive('scroll-touch', {
bind(el, binding) {
let startY, moveY;
el.addEventListener('touchstart', (e) => {
startY = e.touches[0].clientY;
});
el.addEventListener('touchmove', (e) => {
moveY = e.touches[0].clientY - startY;
el.scrollTop -= moveY;
startY = e.touches[0].clientY;
});
}
});
// 使用方式
<div v-scroll-touch class="scroll-area">...</div>
动态加载数据滚动
结合 @scroll 事件实现无限滚动加载:
<template>
<div class="list-container" @scroll="handleScroll">
<div v-for="item in visibleItems" :key="item.id">{{ item.text }}</div>
<div v-if="loading">Loading...</div>
</div>
</template>
<script>
export default {
methods: {
handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target;
if (scrollHeight - (scrollTop + clientHeight) < 50) {
this.loadMore();
}
}
}
};
</script>
横向滚动实现
通过 CSS 的 white-space 和 overflow-x 实现横向滚动:
<template>
<div class="horizontal-scroll">
<div v-for="item in items" :key="item.id" class="item">{{ item.text }}</div>
</div>
</template>
<style>
.horizontal-scroll {
white-space: nowrap;
overflow-x: auto;
}
.item {
display: inline-block;
width: 100px;
}
</style>
每种方法适用于不同场景,原生 CSS 方案最简单,第三方库功能更丰富,自定义指令适合特定交互需求,动态加载适合大数据列表。






