【无标题】try it

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个使用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设置了目录和内容的样式。 希望这个示例对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值