vue怎么实现文本代码实现
Vue 文本代码实现方法
在Vue中实现文本代码展示通常涉及代码高亮、动态渲染或静态展示。以下是几种常见方法:
使用 <pre> 和 <code> 标签
通过HTML原生标签包裹代码,适合静态展示:
<template>
<pre><code>{{ codeText }}</code></pre>
</template>
<script>
export default {
data() {
return {
codeText: 'const example = "Hello Vue";'
}
}
}
</script>
借助语法高亮库(如highlight.js)
安装highlight.js并集成到Vue中:
npm install highlight.js
在Vue组件中注册并使用:

import hljs from 'highlight.js';
import 'highlight.js/styles/github.css'; // 选择样式主题
export default {
mounted() {
document.querySelectorAll('pre code').forEach(block => {
hljs.highlightBlock(block);
});
},
data() {
return {
codeText: 'function test() {\n console.log("highlighted");\n}'
}
}
}
使用第三方Vue组件(如vue-code-highlight)
安装专用Vue组件库:
npm install vue-code-highlight
在组件中直接调用:

<template>
<vue-code-highlight language="javascript">
{{ codeText }}
</vue-code-highlight>
</template>
<script>
import { component } from 'vue-code-highlight';
export default {
components: { 'vue-code-highlight': component },
data() {
return {
codeText: 'export default { name: "Demo" }'
}
}
}
</script>
动态渲染代码(结合v-html)
注意:需确保内容安全性,避免XSS攻击
<template>
<div v-html="formattedCode"></div>
</template>
<script>
export default {
computed: {
formattedCode() {
return `<pre><code>${this.codeText}</code></pre>`;
}
},
data() {
return {
codeText: '<div v-if="show">Dynamic</div>'
}
}
}
</script>
行内代码样式处理
通过CSS自定义代码块样式:
pre {
background: #f5f5f5;
padding: 12px;
border-radius: 4px;
}
code {
font-family: 'Courier New', monospace;
color: #e83e8c;
}
根据需求选择合适的方法:
- 简单展示:原生标签+CSS
- 需要高亮:highlight.js或专用组件
- 动态内容:结合v-html(需谨慎处理安全)






