好的,以下是一个使用Vue和markdown-it实现生成目录和跳转的完整代码示例:
```html
<template>
<div class="markdown-wrapper">
<div class="markdown-toc">
<h3>目录</h3>
<ul>
<li v-for="item in toc" :key="item.id">
<a :href="`#${item.id}`">{{ item.text }}</a>
</li>
</ul>
</div>
<div class="markdown-body" v-html="html"></div>
</div>
</template>
<script>
import MarkdownIt from 'markdown-it'
export default {
name: 'Markdown',
props: ['markdown'],
data() {
return {
html: '',
toc: []
}
},
created() {
const md = new MarkdownIt({
html: true,
linkify: true,
typographer: true,
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(lang, str).value
} catch (__) {}
}
return '' // Use external default escaping
}
})
// 解析markdown
const result = md.parse(this.markdown)
// 处理标题,生成目录
let toc = []
let headingLevel = [0, 0, 0, 0, 0, 0]
let headingCount = 0
let html = ''
for (let i = 0; i < result.length; i++) {
const token = result[i]
if (token.type === 'heading_open') {
const level = parseInt(token.tag.slice(1))
if (level > 2) {
token.attrSet('id', `heading-${++headingCount}`)
toc.push({
id: `heading-${headingCount}`,
text: token.children[0].content,
level
})
}
headingLevel[level - 1]++
for (let j = level; j < headingLevel.length; j++) {
headingLevel[j] = 0
}
token.attrSet('id', `${headingLevel.slice(0, level).join('.')}`)
}
html += md.renderer.renderToken(token)
}
this.html = html
this.toc = toc
}
}
</script>
<style scoped>
.markdown-toc {
position: fixed;
top: 80px;
right: 50px;
width: 200px;
border: 1px solid #ccc;
padding: 10px;
}
.markdown-toc ul {
list-style: none;
padding: 0;
margin: 0;
}
.markdown-toc li {
margin-left: 1em;
}
.markdown-toc li a {
color: #333;
text-decoration: none;
}
.markdown-toc li a:hover {
text-decoration: underline;
}
.markdown-body {
margin: 100px 300px;
}
.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
margin-top: 2em;
}
.markdown-body h1:first-child,
.markdown-body h2:first-child,
.markdown-body h3:first-child,
.markdown-body h4:first-child,
.markdown-body h5:first-child,
.markdown-body h6:first-child {
margin-top: 0;
}
</style>
```
在这个示例中,我们使用Vue和markdown-it实现了解析markdown并生成目录和跳转的功能。首先,在`created`生命周期中,我们使用markdown-it解析markdown,并遍历解析结果来处理标题和生成目录。在处理标题时,我们为每个标题设置一个唯一的id,并将其添加到目录中。在生成目录时,我们只考虑h3、h4、h5和h6,因为h1和h2通常用于页面标题和副标题中。然后,在模板中,我们使用`v-for`指令循环渲染目录和设置标题的跳转链接。最后,我们使用CSS设置了目录和内容的样式。
希望这个示例对你有所帮助!