vue怎么实现文本代码实现
Vue 实现文本代码展示的方法
在 Vue 中展示代码块或格式化文本,可以通过多种方式实现。以下是几种常见方法:
使用 <pre> 和 <code> 标签
最简单的原生 HTML 方式,适合展示简单代码片段:
<template>
<pre><code>{{ codeText }}</code></pre>
</template>
<script>
export default {
data() {
return {
codeText: 'const message = "Hello Vue!";'
}
}
}
</script>
使用语法高亮库
对于需要语法高亮的代码展示,推荐使用专门的库如 highlight.js:
安装依赖:
npm install highlight.js
组件实现:
<template>
<div>
<pre v-highlightjs><code class="javascript">{{ code }}</code></pre>
</div>
</template>
<script>
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
export default {
directives: {
highlightjs(el) {
const blocks = el.querySelectorAll('code')
blocks.forEach(block => {
hljs.highlightElement(block)
})
}
},
data() {
return {
code: 'export default {\n data() {\n return {\n count: 0\n }\n }\n}'
}
}
}
</script>
使用第三方组件
vue-code-highlight 等现成组件可以简化实现:
安装:
npm install vue-code-highlight
使用示例:
<template>
<vue-code-highlight language="js">
{{ code }}
</vue-code-highlight>
</template>
<script>
import { component as VueCodeHighlight } from 'vue-code-highlight'
export default {
components: {
VueCodeHighlight
},
data() {
return {
code: 'console.log("Vue code highlight")'
}
}
}
</script>
动态代码展示
需要动态更新显示的代码时,可以使用计算属性或 watch:
<template>
<pre><code class="javascript">{{ formattedCode }}</code></pre>
</template>
<script>
export default {
props: ['rawCode'],
computed: {
formattedCode() {
return this.rawCode.trim()
}
}
}
</script>
行号显示
添加行号可以通过 CSS 计数器实现:
pre {
counter-reset: line;
}
code:before {
counter-increment: line;
content: counter(line);
display: inline-block;
width: 2em;
padding-right: 1em;
color: #999;
border-right: 1px solid #ddd;
margin-right: 0.5em;
}
代码编辑器集成
对于需要编辑功能的场景,可以集成 Monaco Editor:
npm install monaco-editor
基本使用:
<template>
<div ref="editor" style="height: 300px"></div>
</template>
<script>
import * as monaco from 'monaco-editor'
export default {
mounted() {
monaco.editor.create(this.$refs.editor, {
value: '// Type your code here',
language: 'javascript',
theme: 'vs-dark'
})
}
}
</script>
以上方法可以根据具体需求选择使用,从简单展示到完整编辑功能都能覆盖。





