上篇说到引入v-md-editor编辑markdowm文档并回显,接下来就是根据回显的文档生成导航目录。利用v-md-editor的自定义锚点可以实现此效果:v-md-editor自定义锚点。 官网上的示例是选项式api的,但是这个项目用的是组合式api,所以根据官网内容做了些改动。
1.页面大体布局如下
<template>
<div>
<el-row>
<el-col :span="4">
<div class="catalog">
<div
:key="anchor"
v-for="anchor in titles"
:style="{ padding: `10px 0 10px ${anchor.indent * 20}px` }"
@click="handleAnchorClick(anchor)">
<a style="cursor: pointer">{{ anchor.title }}</a>
</div>
</div>
</el-col>
<el-col :span="14">
<v-md-preview ref="preview" :text="blog.content"></v-md-preview>
</el-col>
<el-col :span="6">
可弹出/隐藏的评论区
</el-col>
</el-row>
</div>
</template>
- 获取markdowm文档生成的html中的h1-h6元素,再获取这些元素中的内容生成目录
const getCatalog = ()=>{
const anchors = preview.value.$el.querySelectorAll("h1,h2,h3,h4,h5,h6");
titles.value = Array.from(anchors).filter(
(title:any) => !!title.innerText.trim() //过滤文本内容不为空的要素
);
if (!titles.value.length) {
titles.value = [];
return;
}
const hTags = Array.from(
new Set(titles.value.map((title:any) => title.tagName))
).sort();
titles.value = titles.value.map((el:any) => ({
title: el.innerText,
lineIndex: el.getAttribute("data-v-md-line"),
indent: hTags.indexOf(el.tagName),
}));
}
3.目录点击事件
function handleAnchorClick(anchor:any) {
const heading = preview.value.$el.querySelector(
`[data-v-md-line="${anchor.lineIndex}"]`
);
if (heading) {
heading.scrollIntoView({
behavior: "smooth",
block: 'start'
});
}
}
- 获取博客内容数据后调用生成目录的方法
const blog = reactive(new blogClass());
//查找文章
const getPassageDetail = ()=>{
blogAPI.selectPassageById(passageId).then((res)=>{
Object.assign(blog,res.data);
console.log(res)
//先生成html文档再生成目录
nextTick(()=>{
getCatalog();
})
})
}
到此生成博客导航目录就完成了,效果如下