vue代码框实现
Vue 代码框实现方法
在 Vue 中实现代码框功能通常需要结合语法高亮库或 UI 组件库。以下是几种常见实现方式:
使用第三方库 Prism.js
安装 Prism.js 及相关依赖:
npm install prismjs
在 Vue 组件中使用:
<template>
<pre><code class="language-javascript">{{ code }}</code></pre>
</template>
<script>
import Prism from 'prismjs';
import 'prismjs/themes/prism.css';
export default {
data() {
return {
code: 'const message = "Hello World";\nconsole.log(message);'
}
},
mounted() {
Prism.highlightAll();
}
}
</script>
使用 highlight.js
安装 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.highlightBlock(block);
});
}
},
data() {
return {
code: 'function test() {\n return "test";\n}'
}
}
}
</script>
使用 UI 组件库
Element UI 实现方式:
<template>
<el-card>
<pre><code class="language-js">{{ code }}</code></pre>
</el-card>
</template>
Vuetify 实现方式:
<template>
<v-card>
<v-card-text>
<pre><code>{{ code }}</code></pre>
</v-card-text>
</v-card>
</template>
自定义样式实现
纯 CSS 实现基础代码框:
<template>
<div class="code-container">
<pre><code>{{ code }}</code></pre>
</div>
</template>
<style>
.code-container {
background: #f5f5f5;
border-radius: 4px;
padding: 16px;
overflow-x: auto;
}
.code-container code {
font-family: 'Courier New', monospace;
color: #333;
}
</style>
动态代码高亮
对于需要动态更新的代码内容:
<template>
<div>
<textarea v-model="rawCode"></textarea>
<pre><code class="language-js" ref="codeBlock">{{ rawCode }}</code></pre>
</div>
</template>
<script>
import Prism from 'prismjs';
export default {
data() {
return {
rawCode: ''
}
},
watch: {
rawCode() {
this.$nextTick(() => {
Prism.highlightElement(this.$refs.codeBlock);
});
}
}
}
</script>
每种方法各有优劣,Prism.js 和 highlight.js 提供完善的语法高亮功能,而 UI 组件库则提供更丰富的样式和交互功能。根据项目需求选择合适方案即可。







