vue怎么实现文本代码实现
Vue 实现文本代码展示的方法
在 Vue 中展示代码文本通常需要结合语法高亮和格式化的功能,以下是几种常见的实现方式:
使用 <pre> 和 <code> 标签
通过 HTML 原生标签包裹代码文本,保留原始格式和缩进:
<template>
<pre><code>{{ codeText }}</code></pre>
</template>
<script>
export default {
data() {
return {
codeText: 'const message = "Hello Vue";\nconsole.log(message);'
}
}
}
</script>
结合语法高亮库(如 highlight.js) 安装 highlight.js 并注册为 Vue 全局组件或局部组件:
npm install highlight.js
在 Vue 中注册并使用:
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css'; // 选择样式主题
Vue.directive('highlight', {
inserted(el) {
hljs.highlightBlock(el);
}
});
模板中使用:
<pre v-highlight><code class="javascript">const foo = () => 'bar';</code></pre>
使用第三方 Vue 组件(如 vue-prism-editor) 安装组件库:
npm install vue-prism-editor prismjs
实现示例:
import { PrismEditor } from 'vue-prism-editor';
import 'vue-prism-editor/dist/prismeditor.min.css';
export default {
components: { PrismEditor },
data() {
return {
code: 'console.log("动态代码")'
}
}
}
模板调用:
<prism-editor v-model="code" language="js" line-numbers />
动态代码渲染的注意事项
当需要动态渲染用户输入的代码时,应避免直接使用 v-html 以防止 XSS 攻击。建议通过以下方式处理:
// 使用 DOMPurify 清理危险内容
import DOMPurify from 'dompurify';
const safeCode = DOMPurify.sanitize(userInputCode);
对于需要交互的代码编辑器场景,可集成 Monaco Editor(VS Code 同款引擎):
npm install monaco-editor
封装组件示例:
import * as monaco from 'monaco-editor';
export default {
mounted() {
this.editor = monaco.editor.create(
this.$refs.editorContainer,
{
value: this.code,
language: 'javascript'
}
);
}
}






