当前位置: 首页 > news >正文

Vue3实现锚点定位

效果演示

代码:

<script lang="ts" setup>
/** 使用 ref 管理锚点元素 */
const abTcomptionRef = ref<HTMLElement | null>(null);
const openClassessRef = ref<HTMLElement | null>(null);
const contestPrivilegesRef = ref<HTMLElement | null>(null);
const competitionExamplesRef = ref<HTMLElement | null>(null);
const conDynamicsRef = ref<HTMLElement | null>(null);

const titleList = reactive([
  { name: 'first', path: 'abTcomption' },
  { name: 'second', path: 'openClassess' },
  { name: 'three', path: 'contestPrivileges' },
  { name: 'four', path: 'competitionExamples' },
  { name: 'five', path: 'conDynamics' }
])
const anchorRefs = {
  abTcomption: abTcomptionRef,
  openClassess: openClassessRef,
  contestPrivileges: contestPrivilegesRef,
  competitionExamples: competitionExamplesRef,
  conDynamics: conDynamicsRef
}; 
const elementList = reactive([
  {
    name: 'first',
    ref: 'abTcomptionRef',
    path: 'abTcomption',
    component: shallowRef(aboutTheCompetition),
    color: '#252635'
    //   show: Number(props.type) === 1,
  },
  {
    name: 'second',
    ref: 'openClassessRef',
    path: 'openClassess',
    component: shallowRef(openClasses),
    color: '#0A0B15',
    showMore: true,
    pageMore: false
  },
  {
    name: 'three',
    ref: 'contestPrivilegesRef',
    path: 'contestPrivileges',
    component: shallowRef(contestPrivileges),
    color: '#252635'
  },
  {
    name: 'four',
    ref: 'competitionExamplesRef',
    path: 'competitionExamples',
    component: shallowRef(competitionExamples),
    color: '#0A0B15',
    showMore: true,
    pageMore: false
  },
  {
    name: 'five',
    ref: 'conDynamicsRef',
    path: 'conDynamics',
    component: shallowRef(contestDynamics),
    color: '#252635',
    showMore: true,
    pageMore: false
  }
])

/** 跳转到锚点位置 */
const anchorPosition = (anchor: string) => {
  const ref2 = anchorRefs[anchor];
  console.log('ref');
  console.log(ref2);
  if (ref2 instanceof Array) {
    ref2[0].scrollIntoView({ behavior: 'smooth' });//设置滚动到实例位置
  } else if (Object.prototype.toString.call(ref2).indexOf('HTMLDivElement') > -1) {
    ref2.scrollIntoView({ behavior: 'smooth' });
  } else {
    console.warn(`未找到锚点元素: ${anchor}`);
  }
};
</script>
<template>
    <div class="flex gap-10 my-20px w-[70%] m-auto">
        <template v-for="(item, index) in titleList" :key="index">
            <div class="tag" :class="{ active: item.path === currentPath }" @click="anchorPosition(item.path)">
            {{ item.name }}
            </div>
        </template>
    </div>
    <div :ref="(el) => { anchorRefs[item.path] = el }"
        v-for="(item, index2) in elementList"
        :style="{ backgroundColor: item.color }"
        :class="['pt-[6px]', !item.showMore||dataList[item.ref]?.length <=3 ? 'pb-[80px]' : 'pb-[40px]']"
        :key="index2">
        <div class="container-title">{{ item.name }}</div>
        <div class="w-[70%] m-auto">
            <component :is="item.component" :dataContent="dataList[item.ref]" />
        </div>
    </div>
</template>

知识点一:

使用shallowRef可以实现浅层响应式引用组件实例,当对象的深层属性发生变化时不会触发视图更新,提高了性能

知识点二:

由于引用组件实例,组件未挂载完成就获取ref,会出现此ref还未完全获取到组件撑开区域的高度,就会出现锚点滚动定位位置错乱的问题,修改ref写法,(el)=> {anchorRefs[item.path] = el }

相关文章:

  • 项目实战:基于Spring WebFlux与LangChain4j实现大语言模型流式输出
  • 服务停止后,自启动的service怎么写
  • QT/C++ 多线程并发下载实践
  • nx-admin1.2版本发布
  • 【教程】如何使用匿名Github仓库: anonymous.4open.science
  • 【蓝桥杯】单片机设计与开发,RTC实时时钟
  • 微信小程序使用 Vant Weapp 组件库教程
  • 迅为RK3568开发板helloworld 驱动实验-驱动编写
  • Python 自动化:节省时间,更智能地工作
  • Python小练习系列 Vol.12:学生信息排序(sorted + key函数)
  • 1.2 基于卷积神经网络与SE注意力的轴承故障诊断
  • Spring 面经
  • 生物化学笔记:医学免疫学原理11 免疫应答 + 固有免疫应答占位效应 + 适应性免疫应答 IgM和IgG抗体用于判断感染时期
  • 【C语言】深入理解指针(三):C语言中的高级指针应用
  • Linux centos 7 服务器组建与管理
  • 2025年 APP测试要点汇总!
  • docker存储卷及dockers容器源码部署httpd
  • Tomcat中的webapps的访问方式和java -jar内置Tomcat的访问方式的区别
  • 【MVP 和 MVVM 相比 MVC 有哪些优化点?】
  • 【MySQL篇】从零开始:解锁数据库的神秘面纱
  • 外交部:国际调解院着眼以调解定分止争,更好维护国际公平正义
  • 安徽凤阳通报鼓楼瓦片脱落:2023年曾维修,已成立调查组
  • 技术派|台军首次试射“海马斯”火箭炮,如何压制这种武器?
  • 杨国荣︱以经验说事:思想史研究中一种需要反思的现象
  • 民间打拐志愿者上官正义遭人身安全威胁,杭州公安:已立案
  • 上海国际碳中和博览会下月举办,首次打造民营经济专区