在 vue 中实现代码块高亮,即<pre><code>
标签中用于直接在页面中展示的代码,增加高亮显示的效果,可以使用 highlight.js
来帮助我们实现。
一、首先下载 highlight.js
npm install highlight.js -S --registry=https://registry.npm.taobao.org
二、然后在工程的 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;
三、使用
- 在代码块的父标签中使用自定义命令
v-highlight
,子元素中的<pre>
和<code>
标签中的代码便会自动高亮。
<div v-highlight>
<pre>
<code>
function() {
console.log(\"Hello world!\");
}
</code>
</pre>
</div>
- 如果代码块没有被包含在
<pre>
和<code>
标签中,可以使用vue.$hljs.highlightAuto("...").value
来格式化代码,然后再将格式化之后的代码渲染到页面上。
<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(row.message).value;
this.codeHtml = html;
}
}
}
</script>
四、可用样式风格
引入样式在 "highlight.js/styles/"
中,引用时将样式名字大写转小写并将名字之间的空格替换为"-"
,再在最后添加 ".css"
后缀,例如:Github Gist → github-gist.css
- Default
- A 11 Y Dark
- A 11 Y Light
- Agate
- An Old Hope
- Androidstudio
- Arduino Light
- Arta
- Ascetic
- Atelier Cave Dark
- Atelier Cave Light
- Atelier Dune Dark
- Atelier Dune Light
- Atelier Estuary Dark
- Atelier Estuary Light
- Atelier Forest Dark
- Atelier Forest Light
- Atelier Heath Dark
- Atelier Heath Light
- Atelier Lakeside Dark
- Atelier Lakeside Light
- Atelier Plateau Dark
- Atelier Plateau Light
- Atelier Savanna Dark
- Atelier Savanna Light
- Atelier Seaside Dark
- Atelier Seaside Light
- Atelier Sulphurpool Dark
- Atelier Sulphurpool Light
- Atom One Dark Reasonable
- Atom One Dark
- Atom One Light
- Brown Paper
- Codepen Embed
- Color Brewer
- Darcula
- Dark
- Docco
- Dracula
- Far
- Foundation
- Github Gist
- Github
- Gml
- Googlecode
- Gradient Dark
- Gradient Light
- Grayscale
- Gruvbox Dark
- Gruvbox Light
- Hopscotch
- Hybrid
- Idea
- Ir Black
- Isbl Editor Dark
- Isbl Editor Light
- Kimbie Dark
- Kimbie Light
- Lightfair
- Lioshi
- Magula
- Mono Blue
- Monokai Sublime
- Monokai
- Night Owl
- Nnfx Dark
- Nnfx
- Nord
- Obsidian
- Ocean
- Paraiso Dark
- Paraiso Light
- Pojoaque
- Purebasic
- Qtcreator Dark
- Qtcreator Light
- Railscasts
- Rainbow
- Routeros
- School Book
- Shades Of Purple
- Solarized Dark
- Solarized Light
- Srcery
- Stackoverflow Dark
- Stackoverflow Light
- Sunburst
- Tomorrow Night Blue
- Tomorrow Night Bright
- Tomorrow Night Eighties
- Tomorrow Night
- Tomorrow
- Vs
- Vs 2015
- Xcode
- Xt 256
- Zenburn
网友评论