🚀 个人简介:某大型测绘遥感企业资深Webgis开发工程师,软件设计师(中级)、优快云优质创作者
💟 作 者:柳晓黑胡椒❣️
📝 专 栏:vue实践
🌈 若有帮助,还请关注 ➕ 点赞➕收藏,不行的话我再努努力💪💪💪
当列表数据过长,需要通过边上的字符按钮点击,通过滚动条跳转到相对于的位置
可以通过 scrollTop 动态的调整滚动条实现
具体思路:
效果链接
1.通过当前 findIndex 方法获取第一个出现该字符的 index
2.通过调整 scrollTop 使定位到目标列表
代码
<template>
<div>
<h3>模拟音乐列表字母定位</h3>
<ul class="list" ref="listRef">
<li class="list-item" :style="{height:itemHeight+'px'}" v-for="(item,index) of data" :key="index">{{ item.label }}</li>
</ul>
<button @click="clickBtn('A')">A</button>
<button @click="clickBtn('B')">B</button>
</div>
</template>
<script lang="ts" setup>
import {reactive, toRefs, ref} from "vue";
import _ from "lodash";
// refs
const listRef = ref<any>({})
const model = reactive({
data: <any>[],
itemHeight: 30
})
const {data,itemHeight} = toRefs(model)
const clickBtn = (str: string) => {
const index = model.data.findIndex((item: any) => item.label[0].toLowerCase() === str.toLowerCase())
console.log(listRef.scrollTop, 2222, index)
listRef.value.scrollTop = index * model.itemHeight;
}
// 异步数据
setTimeout(() => {
model.data =
[
..._.fill(new Array(100), {label: 'Asss'}),
..._.fill(new Array(100), {label: 'Bsss'})
]
console.log(model.data)
}, 1000)
</script>
<style lang="scss" scoped>
.list {
width: 500px;
height: 400px;
padding: 0 20px;
margin: 0;
list-style: none;
overflow-y: auto;
border: 1px solid;
.list-item {
//height: v-bind(itemHeight);
box-sizing: border-box;
}
}
btn {
padding: 10px;
border: 1px solid;
border-radius: 5px;
}
</style>