Vue3 实现文章目录功能

590 阅读1分钟

# 本文已参与「新人创作礼」活动,一起开启掘金创作之路。

实现过程

由于标题之间有父子的关系,所以我们应该用树数据结构来解决这个问题。我们遍历文章容器中的所有标签,如果遇到 

 这类标签,就创建一个节点,将其放到列表中,之后使用 v-for 指令来生成目录就行了。下面分析一下每个节点需要有哪些属性。

一个树的节点,应该具有的属性包括:父节点的指针 parent、子节点的指针列表 children,因为一个节点代表一个标题,所以还要包含:标题的 ID号 id(用于 v-for 的 key),标题名 name(添加了标题的序号)、原始标题名 rawName 和标题的可见性 isVisible,当我们点击标题时,应该滚动到标题的位置,所以还要有 scrollTop 属性。

在我们遍历文章容器中的所有标签时,需要判断当前遇到的标签和上一个标签之间的父子关系,所以要有一个 level 属性代表每一个节点的等级。

下面是具体实现代码:

\

\

.catalog-card {     background: white;     border-radius: 8px;     box-shadow: 0 3px 8px 6px rgba(7, 17, 27, 0.05);     padding: 20px 24px;     width: 100%;     margin-top: 25px;     box-sizing: border-box; } \ .catalog-card-header {     text-align: left !important;     margin-bottom: 15px;     display: flex;     justify-content: space-between;     align-items: center; } \ .catalog-icon {     font-size: 18px;     margin-right: 10px;     color: dodgerblue; } \ .catalog-card-header div > span {     font-size: 17px;     color: #4c4948; } \ .progress {     color: #a9a9a9;     font-style: italic;     font-size: 140%; } \ .catalog-content {     max-height: calc(100vh - 120px);     overflow: auto;     margin-right: -24px;     padding-right: 20px; } \ .catalog-item {     color: #666261;     margin: 5px 0;     line-height: 28px;     cursor: pointer;     transition: all 0.2s ease-in-out;     font-size: 14px;     padding: 2px 6px;     display: -webkit-box;     overflow: hidden;     text-overflow: ellipsis;     -webkit-line-clamp: 1;     -webkit-box-orient: vertical; \     &:hover {         color: #1892ff;     } } \ .active {     background-color: #;     color: white; \     &:hover {         background-color: #0c82e9;         color: white;     } }

来源 | www.cnblogs.com/zhiyiYo/p/1…