要做一个如下图的锚点,ant design vue的锚点样式比较简单,按照官网文档:affix="false" :showInkInFixed="true",就可以显示小方块,但是我试了一下不管用,而且锚点组件不固定起来很不方便,所以放弃这种方法。

之后想过用时间轴和步骤条来模拟锚点,样式很容易达到如图效果,但是在锚点定位上要做太多改造,还是放弃了这种方法。
仔细研究锚点文档,发现可以通过插槽自定义标题,那么想要在文字前面加图标就很简单了。
- <a-anchor @change="onchange">
- <template v-for="(item,index) in items">
- <a-anchor-link :href="'#'+index" @click="onclick(index)">
- <template #title>
- <EnvironmentFilled :style="{fontSize: '16px', color: '#1677ff'}" v-if="index==currentIndex"/>
- <span class="grayBall" v-else>span>
- <span :class="index==currentIndex?'active':''">{{item.title}}span>
- template>
- a-anchor-link>
- template>
- a-anchor>
在文字前面加了图标后,如下图:

css样式上还需要改动,去掉蓝色小条,并且将灰色竖线往右移到图标的中间去,样式如果不生效,就加!important。
- // 隐藏默认的蓝色竖条
- ::v-deep .ant-anchor .ant-anchor-ink {
- display: none!important;
- }
- // 将灰色竖线移到图标中间
- ::v-deep .ant-anchor:before {
- left: 25px!important;
- }
完整代码:
- <div class="container">
- <div class="floor">
- <template v-for="(item,index) in items">
- <div :id="index">
- <template v-for="(item2,index2) in 50">
- <p>{{item.title}}p>
- template>
- div>
- template>
- div>
- <div>
- <a-anchor @change="onchange">
- <template v-for="(item,index) in items">
- <a-anchor-link :href="'#'+index" @click="onclick(index)">
- <template #title>
- <EnvironmentFilled :style="{fontSize: '16px', color: '#1677ff'}" v-if="index==currentIndex"/>
- <span class="grayBall" v-else>span>
- <span :class="index==currentIndex?'active':''">{{item.title}}span>
- template>
- a-anchor-link>
- template>
- a-anchor>
- div>
-
- div>
-
- import { EnvironmentFilled } from '@ant-design/icons-vue';
- import { ref } from 'vue';
- let currentIndex = ref
(0); - const items = ref
([ - {
- title: '个人信息'
- },
- {
- title: '教育背景'
- },
- {
- title: '工作经历'
- }
- ]);
- const onclick = (index : number) => {
- currentIndex.value = index;
- }
- const onchange = (e:string) => {
- //鼠标滚动的时候,锚点也会发生变化,输出的是锚点id
- let index = Number(e.replace('#',''));
- currentIndex.value = index;
- }
-
- .container {
- width: 80%;
- display: flex;
- justify-content: space-end;
- }
-
- .floor {
- width: 30%;
- }
- .grayBall {
- display: inline-block;
- width: 12px;
- height: 12px;
- border-radius: 50%;
- background-color: #eee;
- }
- // 隐藏默认的蓝色竖条
- ::v-deep .ant-anchor .ant-anchor-ink {
- display: none!important;
- }
- // 将灰色竖线移到图标中间
- ::v-deep .ant-anchor:before {
- left: 25px!important;
- }
- .active {
- color:#1677ff
- }
最终效果:
