自定义锚点组件解决在路由为哈希模式下使用antd的anchor组件存在的问题

自定义锚点组件解决在路由为哈希模式下使用antd的anchor组件存在的问题

antd的anchor组件通过修改URL来定位锚点跳转位置,而单页应用中如果使用哈希模式的路由,会导致当前路由没有定义而出现页面空白。

解决方案1——重写antd组件的点击事件

 const handleClick: AnchorProps['onClick'] = (e, link) => {
   e.preventDefault();
   var srcolls = document.getElementById(link.href);
   srcolls.scrollIntoView({block: 'start', behavior: 'smooth'});
 };

解决方案2——自定义组件

话不多说,直接上demo,整个全新的

<template>
  <div>
    <div class="anchor-position">
      <div
        v-for="(item, index) in anchorList"
        :key="index"
        @click="jumpTo(item.id)"
        :class="item.class"
      >
        {{ item.name }}
      </div>
    </div>
    <div id="client" style="height: 500px">客户端 / Delivery</div>
    <div id="message" style="height: 500px">报文</div>
    <div id="session" style="height: 500px">会话</div>
    <div id="api" style="height: 500px">API</div>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  interface anchorListParams {
    name: string;
    id: string;
    class: string;
  }
  export default defineComponent({
    name: 'Measure',
    components: {},
    setup() {
      const anchorList = ref<anchorListParams[]>([
        {
          id: 'client',
          name: '客户端 / Delivery',
          class: 'anchor-item',
        },
        {
          id: 'message',
          name: '报文',
          class: 'anchor-item',
        },
        {
          id: 'session',
          name: '会话',
          class: 'anchor-item',
        },
        {
          id: 'api',
          name: 'API',
          class: 'anchor-item',
        },
        {
          id: 'number',
          name: '消息数',
          class: 'anchor-item',
        },
        {
          id: 'flow',
          name: '流量收发(字节)',
          class: 'anchor-item',
        },
      ]);
      const jumpTo = (id: string) => {
        anchorList.value.forEach((item: anchorListParams) => {
          item.class = 'anchor-item';
          if (item.id === id) item.class = 'anchor-item item-click';
        });
        let srcolls = document.getElementById(id);
        srcolls?.scrollIntoView({ block: 'start', behavior: 'smooth' });
      };
      return {
        anchorList,
        jumpTo,
      };
    },
  });
</script>
<style scoped lang="less">
  .anchor-position {
    position: fixed;
    right: 35px;
    top: 347px;
    width: 125px;
    border-left: 2px solid #d1deed;
    .anchor-item {
      margin: 7px 0;
      display: flex;
      align-items: center;
      padding-left: 14px;
      cursor: pointer;
      &:hover {
        background: rgba(213, 234, 255, 0.66);
      }
    }
    .item-click {
      color: #2896ff;
      border-left: 4px solid #2896ff;
    }
  }
</style>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值