vue 实现滑动
Vue 实现滑动效果的方法
使用第三方库(如 vue-smooth-scroll)
安装 vue-smooth-scroll 库:
npm install vue-smooth-scroll
在 Vue 组件中引入并使用:
import Vue from 'vue'
import VueSmoothScroll from 'vue-smooth-scroll'
Vue.use(VueSmoothScroll)
模板中使用指令实现平滑滚动:
<button v-smooth-scroll="{ duration: 1000, offset: -50 }">Scroll to Section</button>
<section id="target-section">Target Content</section>
使用原生 JavaScript 方法
通过 ref 获取 DOM 元素并调用 scrollIntoView:
methods: {
scrollToElement() {
this.$refs.targetElement.scrollIntoView({ behavior: 'smooth' })
}
}
模板结构:
<button @click="scrollToElement">Scroll</button>
<div ref="targetElement">Content to scroll to</div>
实现横向滑动组件
使用 CSS 结合 touch 事件实现:

<div class="scroll-container" ref="container"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove">
<div class="scroll-content">
<!-- 滑动内容 -->
</div>
</div>
脚本部分:
data() {
return {
startX: 0,
scrollLeft: 0
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].pageX
this.scrollLeft = this.$refs.container.scrollLeft
},
handleTouchMove(e) {
const x = e.touches[0].pageX
const walk = (x - this.startX) * 2
this.$refs.container.scrollLeft = this.scrollLeft - walk
}
}
CSS 样式:
.scroll-container {
overflow-x: auto;
white-space: nowrap;
-webkit-overflow-scrolling: touch;
}
.scroll-content {
display: inline-block;
}
使用 CSS Scroll Snap
纯 CSS 解决方案:

<div class="snap-container">
<div class="snap-item">Item 1</div>
<div class="snap-item">Item 2</div>
</div>
CSS 样式:
.snap-container {
scroll-snap-type: x mandatory;
overflow-x: auto;
display: flex;
}
.snap-item {
scroll-snap-align: start;
flex: 0 0 auto;
}
性能优化建议
对于大量滑动内容,建议使用虚拟滚动技术。可以借助 vue-virtual-scroller 等库:
npm install vue-virtual-scroller
基础用法示例:
import { RecycleScroller } from 'vue-virtual-scroller'
export default {
components: { RecycleScroller }
}
模板结构:
<RecycleScroller
class="scroller"
:items="items"
:item-size="50"
key-field="id">
<template v-slot="{ item }">
<!-- 渲染单个项目 -->
</template>
</RecycleScroller>






