vue滑动页面怎么实现
Vue 滑动页面实现方法
使用原生 CSS 实现滚动
通过 CSS 的 overflow 属性控制容器滚动行为。适用于简单场景,无需额外依赖。
<template>
<div class="scroll-container">
<!-- 内容区域 -->
</div>
</template>
<style>
.scroll-container {
height: 100vh;
overflow-y: auto;
}
</style>
使用 better-scroll 库
专门处理移动端滚动的轻量级库,支持惯性滚动、边界回弹等效果。
安装依赖:
npm install @better-scroll/core
示例代码:
<template>
<div ref="wrapper" class="scroll-wrapper">
<div class="scroll-content">
<!-- 滚动内容 -->
</div>
</div>
</template>
<script>
import BScroll from '@better-scroll/core'
export default {
mounted() {
this.bs = new BScroll(this.$refs.wrapper, {
scrollY: true,
click: true
})
},
beforeDestroy() {
this.bs.destroy()
}
}
</script>
<style>
.scroll-wrapper {
height: 100vh;
overflow: hidden;
}
</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 }">
<!-- 单条内容模板 -->
</template>
</RecycleScroller>
</template>
<script>
import { RecycleScroller } from 'vue-virtual-scroller'
export default {
components: { RecycleScroller },
data() {
return {
items: [] // 数据源
}
}
}
</script>
<style>
.scroller {
height: 100vh;
}
</style>
实现横向滑动
通过 CSS 的 white-space 和 overflow-x 属性组合实现。
<template>
<div class="horizontal-scroll">
<div class="scroll-content">
<!-- 横向排列的内容 -->
</div>
</div>
</template>
<style>
.horizontal-scroll {
width: 100%;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
.scroll-content {
display: inline-block;
white-space: nowrap;
}
</style>
监听滚动事件
通过 @scroll 事件实现滚动监听逻辑。
<template>
<div class="scrollable" @scroll="handleScroll">
<!-- 内容 -->
</div>
</template>
<script>
export default {
methods: {
handleScroll(e) {
const { scrollTop, scrollHeight, clientHeight } = e.target
if (scrollHeight - scrollTop === clientHeight) {
// 到达底部逻辑
}
}
}
}
</script>
注意事项
- 移动端需添加
-webkit-overflow-scrolling: touch启用惯性滚动 - 虚拟滚动适合大数据量场景,但需要精确设置
item-size - better-scroll 初始化需确保 DOM 已渲染完成
- 横向滑动需设置
white-space: nowrap防止内容换行







