官方提供了监听页面滚动事件控制索引跳转,但是一旦封装了组件就无法实现监听效果,本文基于scroll-view的scroll-into-view属性实现点击索引跳转;通过
uni .createSelectorQuery().selectAll监听实现滚动标记
废话不多说直接上代码
<template>
<view>
<!-- 滚动内容 -->
<scroll-view class="home" :scroll-y="true" :scroll-into-view="intoViewId" scroll-with-animation @scroll="scroll">
<!-- 循环索引栏 -->
<view v-for="(item, index) in indexList" :key="index" :id="'i' + index" class="indexItem">
<text>{{ item }}</text>
<!-- 根据索引栏id查找显示内容 -->
<view class="itemArr" v-for="(v, i) in itemArr[index]" :key="i">
{{ v }}
</view>
</view>
</scroll-view>
<!-- 侧边索引栏 -->
<view class="indexList">
<view
:class="{ isActive: activeId === `i${index}` }"
v-for="(item, index) in indexList"
@click="toID(index)"
:key="index">
{{ item }}
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
intoViewId: null,
activeId: "i0",
indexList: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],
itemArr: [
["列表A1", "列表A2", "列表A3"],
["列表B1", "列表B2", "列表B3"],
["列表C1", "列表C2", "列表C3"],
["列表D1", "列表D2", "列表D3"],
["列表E1", "列表E2", "列表E3"],
["列表F1", "列表F2", "列表F3"],
["列表G1", "列表G2", "列表G3"],
["列表H1", "列表H2", "列表H3"],
["列表I1", "列表I2", "列表I3"],
["列表J1", "列表J2", "列表J3"],
],
};
},
methods: {
toID(index) {
console.log(123);
const id = "i" + index;
console.log(id);
this.intoViewId = id;
},
indexClick(e) {
console.log(e);
},
scroll(e) {
//获取scroll-view中展示的元素
uni
.createSelectorQuery()
.selectAll(".indexItem")
.boundingClientRect((data) => {
const showArr = data.filter((item) => {
return item.top >= 0;
});
//获取第一个元素的id
const id = showArr[0].id;
console.log(id);
//设置选中的id
this.activeId = id;
})
.exec();
},
},
};
</script>
<style lang="scss" scoped>
.indexList {
display: flex;
flex-direction: column;
width: 20px;
background-color: #eee;
position: fixed;
top: 50px;
right: 20px;
align-items: center;
}
.home {
height: 300px;
}
.itemArr {
margin: 30px auto;
}
.isActive {
color: rgb(28, 163, 204);
}
</style>