vue实现代码块
在Vue中实现代码块
使用<pre>和<code>标签
在Vue模板中可以直接使用HTML的<pre>和<code>标签来包裹代码内容。这种方式简单直接,适合静态代码展示。
<template>
<pre><code>
function helloWorld() {
console.log('Hello, World!');
}
</code></pre>
</template>
使用第三方库highlight.js
highlight.js是一个流行的代码高亮库,支持多种编程语言。通过Vue的指令或组件可以方便地集成。
安装highlight.js:
npm install highlight.js
在Vue组件中使用:
<template>
<pre v-highlightjs><code class="javascript">
function helloWorld() {
console.log('Hello, World!');
}
</code></pre>
</template>
<script>
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';
export default {
directives: {
highlightjs(el) {
hljs.highlightElement(el);
}
}
};
</script>
使用prismjs
prismjs是另一个强大的代码高亮库,支持更多自定义选项。
安装prismjs:
npm install prismjs
在Vue组件中使用:
<template>
<pre><code class="language-javascript">
function helloWorld() {
console.log('Hello, World!');
}
</code></pre>
</template>
<script>
import Prism from 'prismjs';
import 'prismjs/themes/prism.css';
export default {
mounted() {
Prism.highlightAll();
}
};
</script>
动态代码块
如果需要动态渲染代码块,可以通过Vue的v-for或v-if指令结合上述方法实现。
<template>
<div>
<pre v-for="(code, index) in codeBlocks" :key="index">
<code class="language-javascript">{{ code }}</code>
</pre>
</div>
</template>
<script>
export default {
data() {
return {
codeBlocks: [
'function hello() { console.log("Hello"); }',
'function world() { console.log("World"); }'
]
};
}
};
</script>
使用Vue插件vue-code-highlight
vue-code-highlight是一个专门为Vue设计的代码高亮插件,简化了集成过程。
安装插件:
npm install vue-code-highlight
在Vue中使用:
<template>
<vue-code-highlight language="javascript">
function helloWorld() {
console.log('Hello, World!');
}
</vue-code-highlight>
</template>
<script>
import VueCodeHighlight from 'vue-code-highlight';
export default {
components: {
VueCodeHighlight
}
};
</script>
以上方法可以根据具体需求选择,静态内容推荐使用<pre>和<code>标签,动态或复杂场景推荐使用highlight.js或prismjs。







