赞
踩
const msgData=[{id:1,name:'2'}] //数据源
const itemHeight = 50 // 每一个数组对象的高度
const visualHeight = 500 //可视区域的
const rollHeight = itemHeight * msgData.length // 滚动区域的总高度
const itemCount = Math.ceil(visualHeight / itemHeight) //计算展示出来的数量
const container = ref(null)
const start = ref(0)
const translateY = ref(0)
// 监听数组在可视区域显示的变化
const dataList = computed(() => {
return msgData.slice(start.value, start.value + itemCount)
})
onMounted(() => {
container.value.addEventListener('scroll', e => { // 添加滚动事件
const { scrollTop } = e.target //解构滚动内容区域
start.value = Math.floor(scrollTop / itemHeight) // 计算滚动个数,替换几个数
translateY.value = scrollTop + 'px' //平移
})
})
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://unpkg.com/vue@next"></script> <style> * { margin: 0; } .content { overflow: auto; display: flex; } </style> </head> <div id="app"> <div class="content" ref="container" :style="{ height: visualHeight }"> <div class="empty" :style="{ height: rollHeight }"></div> <div class="list" :style="{ transform: `translateY(${translateY})`}"> <p v-for="item in dataList" :key="item" class="item" :style="{ height: itemHeight }">{{ item.name }}</p> </div> </div> </div> <body> <script> const { ref, onMounted, computed } = Vue const App = { setup() { // 数据 const msgData=[{id:1,name:'1'},] const itemHeight = 50 // 每一个数组对象的高度 const visualHeight = 500 //可视区域的 const rollHeight = itemHeight * msgData.length // 滚动区域的总高度 const itemCount = Math.ceil(visualHeight / itemHeight) //计算展示出来的数量 const container = ref(null) const start = ref(0) const translateY = ref(0) // 监听数组在可视区域显示的变化 const dataList = computed(() => { return msgData.slice(start.value, start.value + itemCount) }) onMounted(() => { // 添加滚动事件 container.value.addEventListener('scroll', e => { const { scrollTop } = e.target //解构滚动内容区域 start.value = Math.floor(scrollTop / itemHeight) // 计算滚动个数,替换几个数 translateY.value = scrollTop + 'px' //平移 }) }) return { dataList, container, translateY, visualHeight: `${visualHeight}px`, itemHeight: `${itemHeight}px`, rollHeight: `${rollHeight}px` } } } Vue.createApp(App).mount('#app') </script> </body> </html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。