自定义锚点组件解决在路由为哈希模式下使用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>