本文主要是介绍vue3组件 描点定位以及监听滚动切换对应activeTab,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
描点定位以及监听滚动切换对应activeTab
基本逻辑
- init 初始化 获取滚动区域内所有非文本子节点
- offsetTopArr 存储所有子节点的高度
- scroll 监听滚动的距离,找到还在可视区的元素高度
<template><div class="tab-list"><div v-for="item in menuList" class="item" :class="{ 'is-active': active === item.value }"><a :href="`#${item.value}`" @click="active = item.value">{{ item.label }}</a></div></div><div class="scroll-content" @scroll="handleScroll"><slot /></div>
</template><script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue';
import { throttle } from 'lodash';interface propsType {menuList: Array<{label: string;value: string;}>;parentClass: string;
}
const props = withDefaults(defineProps<propsType>(), {menuList: () => [],
});const active = ref(props.menuList[0].value);const offsetTopArr = ref([]);
const curIndex = ref(0);const init = () => {const parentNode = document.querySelector(props.parentClass);const childNodesAll = parentNode.childNodes;for (let index = 0; index < childNodesAll.length; index++) {const child = childNodesAll[index];if (child.nodeType === 1) offsetTopArr.value.push(child.offsetTop);}
};const handleScroll = throttle((e) => {curIndex.value = offsetTopArr.value.findIndex((item) => {return e.target.scrollTop <= item;});active.value = props.menuList[curIndex.value].value;
}, 200);onMounted(() => {nextTick(init);
});
</script><style lang="scss" scoped>
.tab-list {height: 100%;width: 120px;
}
.scroll-content {width: 100%;height: 100%;overflow-y: auto;
}
</style>
这篇关于vue3组件 描点定位以及监听滚动切换对应activeTab的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!