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

Vue.js中代码块格式化存储后展示格式丢失问题求助

解决Vue/Nuxt中展示数据库存储的格式化代码块问题

核心问题分析

你存在数据库里的是转义后的HTML代码(比如&lt;对应<),直接用<code>标签只会把转义字符原样输出,既不会解析成真实的代码结构,也没法保留换行、缩进这类格式。

解决方案步骤

1. 解析转义字符并保留基础格式

Vue默认会对插值内容做HTML转义,所以需要用v-html指令渲染原始HTML,同时给容器加样式保证格式不丢失:

<template>
  <div class="code-block">
    <pre><code v-html="formattedCode"></code></pre>
  </div>
</template>

<script setup>
// 从数据库取回的原始转义代码
const rawCode = '&lt;template&gt;\n  &lt;!-- some content --&gt;\n  &lt;NuxtErrorBoundary @error=&quot;someErrorLogger&quot;&gt;\n    &lt;!-- You use the default slot to render your content --&gt;\n    &lt;template #error=&quot;{ error, clearError }&quot;&gt;\n      You can display the error locally here: {{ error }}\n      &lt;button @click=&quot;clearError&quot;&gt;\n        This will clear the error.\n      &lt;/button&gt;\n    &lt;/template&gt;\n  &lt;/NuxtErrorBoundary&gt;\n&lt;/template&gt;'

// 直接赋值,v-html会自动解析转义字符
const formattedCode = rawCode
</script>

<style scoped>
.code-block pre {
  background-color: #f5f5f5;
  padding: 1rem;
  border-radius: 4px;
  overflow-x: auto;
}
.code-block code {
  font-family: monospace;
  white-space: pre; /* 强制保留换行和缩进 */
}
</style>

2. 添加语法高亮(推荐)

如果需要代码高亮效果,用highlight.js实现更便捷:

安装依赖

npm install highlight.js
# 或 yarn add highlight.js

组件中引入使用

<template>
  <div class="code-block">
    <pre><code ref="codeElement" v-html="formattedCode"></code></pre>
  </div>
</template>

<script setup>
import hljs from 'highlight.js'
import 'highlight.js/styles/github-dark.css' // 选择你喜欢的主题样式

const rawCode = '&lt;template&gt;\n  &lt;!-- some content --&gt;\n  &lt;NuxtErrorBoundary @error=&quot;someErrorLogger&quot;&gt;\n    &lt;!-- You use the default slot to render your content --&gt;\n    &lt;template #error=&quot;{ error, clearError }&quot;&gt;\n      You can display the error locally here: {{ error }}\n      &lt;button @click=&quot;clearError&quot;&gt;\n        This will clear the error.\n      &lt;/button&gt;\n    &lt;/template&gt;\n  &lt;/NuxtErrorBoundary&gt;\n&lt;/template&gt;'

const formattedCode = rawCode
const codeElement = ref(null)

onMounted(() => {
  if (codeElement.value) {
    hljs.highlightElement(codeElement.value)
  }
})
</script>

<style scoped>
.code-block pre {
  background-color: #1e1e1e; /* 匹配主题的背景色 */
  padding: 1rem;
  border-radius: 4px;
  overflow-x: auto;
}
.code-block code {
  font-family: 'Consolas', 'Monaco', monospace;
  white-space: pre;
}
</style>

3. 注意事项

  • 使用v-html时,务必确保数据库中的代码是安全的,避免引入XSS攻击风险(比如不要直接存储未过滤的用户提交代码)。
  • 若你用的是Nuxt3项目,也可以考虑使用官方的@nuxt/content模块,它自带代码高亮功能,但需要将代码按Markdown格式存储。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 22:05:28