You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nuxt.js中格式化/解析来自Strapi的Markdown格式文章

Nuxt 中 Markdown 转 HTML 渲染方案

通用依赖安装

首先安装 Markdown 解析库:

npm install markdown-it
# 或者用 pnpm
pnpm add markdown-it
# 或者 yarn
yarn add markdown-it

Nuxt 3 实现方式

封装全局解析工具

在 composables 目录下新建 useMarkdown.ts:

import MarkdownIt from 'markdown-it'
// 初始化解析器,可根据需求调整配置
const md = new MarkdownIt({
  html: true, // 允许解析 Markdown 内嵌的 HTML 标签
  linkify: true, // 自动将文本链接转为可点击的 a 标签
  typographer: true // 自动优化排版符号(比如引号、破折号)
})

// 如果内容存在用户投稿等不可控场景,可安装 xss 库做安全过滤
// import xss from 'xss'
// return xss(md.render(content))

export const useMarkdown = (content: string) => {
  return md.render(content)
}

页面/组件内使用

<template>
  <!-- 用 v-html 渲染解析后的 HTML 内容 -->
  <div class="article-content" v-html="htmlContent"></div>
</template>

<script setup>
// 从 Strapi 接口拉取文章数据
const { data: article } = await useFetch('/api/strapi/articles/xxx')
// 解析 Markdown 内容
const htmlContent = useMarkdown(article.value.content)
</script>

<style scoped>
/* 自行编写 Markdown 对应标签的样式,也可直接引入现成的 Markdown 主题 CSS */
.article-content h1 {
  font-size: 2rem;
  font-weight: bold;
  margin: 1.5rem 0;
}
.article-content p {
  line-height: 1.8;
  margin: 1rem 0;
}
/* 其余 h2/h3、列表、代码块等样式按需补充 */
</style>

Nuxt 2 实现方式

封装全局插件

在 plugins 目录下新建 markdown.js:

import MarkdownIt from 'markdown-it'
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true
})

export default ({ app }, inject) => {
  // 注入全局方法
  inject('md', content => md.render(content))
}

在 nuxt.config.js 中注册插件:

export default {
  plugins: [
    '~/plugins/markdown.js'
  ]
}

组件内使用

<template>
  <div class="article-content" v-html="htmlContent"></div>
</template>

<script>
export default {
  async asyncData({ $axios }) {
    const article = await $axios.$get('/api/strapi/articles/xxx')
    return {
      article
    }
  },
  computed: {
    htmlContent() {
      return this.$md(this.article.content)
    }
  }
}
</script>

注意事项

  • 使用 v-html 渲染存在 XSS 注入风险,若内容来源不可控(比如允许用户提交内容),必须额外接入 XSS 过滤库处理解析后的 HTML 内容。
  • 解析后的标签默认没有样式,需要手动为 .article-content 容器下的各类标签编写样式,或者直接引入第三方 Markdown 主题样式包。

内容的提问来源于stack exchange,提问作者Ibra Kadabra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 16:24:03