vue3组件 描点定位以及监听滚动切换对应activeTab

描点定位以及监听滚动切换对应activeTab

基本逻辑

  1. init 初始化 获取滚动区域内所有非文本子节点
  2. offsetTopArr 存储所有子节点的高度
  3. 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>

相关推荐

  1. vue3组件 定位以及监听滚动切换对应activeTab

    2024-04-27 17:28:09       30 阅读
  2. vue3 watchEffect 监听组件变化

    2024-04-27 17:28:09       58 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-27 17:28:09       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-27 17:28:09       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-27 17:28:09       87 阅读
  4. Python语言-面向对象

    2024-04-27 17:28:09       96 阅读

热门阅读

  1. 使用讯飞语音识别----前后端如何交互?

    2024-04-27 17:28:09       40 阅读
  2. 网站推广爬虫

    2024-04-27 17:28:09       28 阅读
  3. 渗透测试基础知识之Web安全教程系列(引言)

    2024-04-27 17:28:09       34 阅读
  4. 企业架构学习 Togaf 2、概述、简介

    2024-04-27 17:28:09       30 阅读
  5. 数据分析-pandas1

    2024-04-27 17:28:09       28 阅读
  6. 企业微信私域:精细化运营与深度挖掘新策略

    2024-04-27 17:28:09       37 阅读