vue实现滚动框
Vue 实现滚动框的方法
使用原生滚动条
在 Vue 中可以直接通过 CSS 控制滚动条样式,结合 overflow 属性实现滚动效果。以下是一个简单的示例:
<template>
<div class="scroll-container">
<div v-for="item in items" :key="item.id" class="scroll-item">
{{ item.content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, content: 'Item 1' },
{ id: 2, content: 'Item 2' },
// 更多数据...
]
}
}
}
</script>
<style>
.scroll-container {
height: 300px;
overflow-y: auto;
border: 1px solid #ddd;
}
.scroll-item {
padding: 10px;
border-bottom: 1px solid #eee;
}
</style>
使用第三方库(如 Better-Scroll)
对于更复杂的滚动需求,可以使用第三方库如 Better-Scroll:
<template>
<div ref="wrapper" class="wrapper">
<div class="content">
<div v-for="item in items" :key="item.id" class="item">
{{ item.content }}
</div>
</div>
</div>
</template>
<script>
import BScroll from '@better-scroll/core'
export default {
data() {
return {
items: [
{ id: 1, content: 'Item 1' },
{ id: 2, content: 'Item 2' },
// 更多数据...
]
}
},
mounted() {
this.scroll = new BScroll(this.$refs.wrapper, {
scrollY: true,
click: true
})
}
}
</script>
<style>
.wrapper {
height: 300px;
overflow: hidden;
}
.content {
padding: 10px;
}
</style>
实现无限滚动
结合 Vue 的 v-infinite-scroll 指令可以实现无限滚动加载:
<template>
<div
class="infinite-scroll-container"
v-infinite-scroll="loadMore"
infinite-scroll-disabled="busy"
infinite-scroll-distance="10"
>
<div v-for="item in items" :key="item.id" class="item">
{{ item.content }}
</div>
<div v-if="loading" class="loading">Loading...</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
page: 1,
busy: false,
loading: false
}
},
methods: {
loadMore() {
this.busy = true
this.loading = true
// 模拟异步加载数据
setTimeout(() => {
const newItems = Array(10).fill().map((_, i) => ({
id: this.items.length + i + 1,
content: `Item ${this.items.length + i + 1}`
}))
this.items = [...this.items, ...newItems]
this.page++
this.busy = false
this.loading = false
}, 1000)
}
}
}
</script>
<style>
.infinite-scroll-container {
height: 500px;
overflow-y: auto;
}
.item {
padding: 15px;
border-bottom: 1px solid #eee;
}
.loading {
text-align: center;
padding: 10px;
}
</style>
自定义滚动条样式
可以通过 CSS 自定义滚动条外观:
/* 适用于 WebKit 浏览器 */
.scroll-container::-webkit-scrollbar {
width: 8px;
}
.scroll-container::-webkit-scrollbar-track {
background: #f1f1f1;
}
.scroll-container::-webkit-scrollbar-thumb {
background: #888;
border-radius: 4px;
}
.scroll-container::-webkit-scrollbar-thumb:hover {
background: #555;
}






