Vue.js中代码块格式化存储后展示格式丢失问题求助
解决Vue/Nuxt中展示数据库存储的格式化代码块问题
核心问题分析
你存在数据库里的是转义后的HTML代码(比如<对应<),直接用<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 = '<template>\n <!-- some content -->\n <NuxtErrorBoundary @error="someErrorLogger">\n <!-- You use the default slot to render your content -->\n <template #error="{ error, clearError }">\n You can display the error locally here: {{ error }}\n <button @click="clearError">\n This will clear the error.\n </button>\n </template>\n </NuxtErrorBoundary>\n</template>' // 直接赋值,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 = '<template>\n <!-- some content -->\n <NuxtErrorBoundary @error="someErrorLogger">\n <!-- You use the default slot to render your content -->\n <template #error="{ error, clearError }">\n You can display the error locally here: {{ error }}\n <button @click="clearError">\n This will clear the error.\n </button>\n </template>\n </NuxtErrorBoundary>\n</template>' 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
相关产品推荐
相关产品推荐

