Implement code highlighting and formatting in vue
To implement code block highlighting in vue, which is
<pre><code>
the code in the tag that is used to display directly on the page, to increase the highlighting effect, you can usehighlight.js
to help us achieve it.
Install highlight.js plug-in
npm install highlight.js -S
Introduced in main.js
// 引入 highlight.js 代码高亮工具
import hljs from "highlight.js";
// 使用样式,有多种样式可选
import "highlight.js/styles/github-gist.css";
// 增加自定义命令v-highlight
Vue.directive("highlight", function(el) {
let blocks = el.querySelectorAll("pre code");
blocks.forEach(block => {
hljs.highlightBlock(block);
});
});
// 增加组定义属性,用于在代码中预处理代码格式
Vue.prototype.$hljs = hljs;
Use it in the component and place it in the code tag under the pre tag.
<div v-highlight> <!-- 使用指令 -->
<pre>
<code class="css"><!-- 声明什么类型的代码 -->
[CSS]
{
width:'100px'
}
</code>
<code class="javascript">
[javascript]
var a = 123;
var b = document.getElementById('tr')
</code>
<code class="html">
[HTML]
<div></div><!-- html代码需要转义 -->
</code>
</pre>
</div>
Used in components if the code block is not included in the <pre>
and <code>
tags
You can use
vue.$hljs.highlightAuto("内容").value
to format the code, and then render the formatted code to the page.
<template>
<div v-html="codeHtml" v-highlight></div>
</template>
<script>
export default {
data() {
return {
codeHtml: ""
}
},
monted() {
this.format();
},
methods: {
format() {
let code = "function() { console.log(\"Hello world!\"); }";
const html = this.$hljs.highlightAuto(code).value;
this.codeHtml = html;
}
}
}
</script>
Available styles
Introduce the style in "highlight.js/styles/"
, when quoting, convert the style name from uppercase to lowercase and replace the spaces between the names with "-"
, and then add ".css"
the suffix at the end
For example: Github Gist → github-gist.css