此篇文章主要是记录下渲染markdown格式字符串的实现,如果是想直接渲染.md结尾的文件,推荐Nuxt Content模块 。
渲染markdown内容自然用的是markdown-it
了,之前找无头cms的时候就想找一个直接返回markdown内容的,而不是返回转换后的html内容,这样的话可以有更多自定义的空间,所以内容后台使用了Strapi 。此外也考虑了JPress和Halo,也都是可用且好用的开源cms。
组件创建
首先是在components
文件夹下创建名为AppContent.vue
的文件,框架会自动引入该组件,到时候只需直接传入字符串使用就好。
template部分内容很简单,渲染转换后的html内容即可。具体如何转换,下面继续说。
<template>
<div class="app-content">
<div v-html="contentHtml" />
</div>
</template>
依赖安装
主要依赖是markdown-it
,然后有一些相关的插件,可以使用表情和特殊符号,建议一起装了。
npm install markdown-it markdown-it-emoji markdown-it-sub markdown-it-sup @shikijs/markdown-it --save
引用
下面是组件完整内容,主要引用了markdown-it并使用相关插件,将渲染后的html内容在组件中展示。高亮组件使用shikijs
,这里推荐下Shiki v1.0 的演变 ·Nuxt博客 --- The Evolution of Shiki v1.0 · Nuxt Blog,里面讲述了antfu
是如何将此库由仅能在Node端运行变成了在浏览器端和Node均能运行的库,这非常适合Nuxt!文章开头提到的Nuxt Content也内置了shikijs
。
<script setup>
import MarkdownIt from 'markdown-it'
import { full as emojiPlugin } from 'markdown-it-emoji'
import subPlugin from 'markdown-it-sub'
import supPlugin from 'markdown-it-sup'
import shikiPlugin from '@shikijs/markdown-it'
// 定义props,到时候传content
const props = defineProps({
content: {
type: String,
default: '',
},
})
const md = MarkdownIt({
html: true,
linkify: true,
typographer: true,
})
md.use(emojiPlugin) // 表情插件
md.use(subPlugin) // 下标符号插件
md.use(supPlugin) // 上标符号插件
// code高亮
md.use(await shikiPlugin({
themes: {
light: 'vitesse-light',
dark: 'vitesse-dark',
},
}))
function mdToHtml(str) {
return md.render(str)
}
// 渲染内容
const contentHtml = computed(() => mdToHtml(props.content))
</script>
<template>
<div class="app-content">
<div v-html="contentHtml" />
</div>
</template>
好了,后续在页面中引用这个组件,传markdown格式的字符串就可以实现字符串渲染。