Skip to main content

代码块高亮

· 2 min read
Kevin

showdown

使用 showdown,可以将 markdown语法的内容转换为 html格式的内容

npm install showdown

使用:

main.js

import showdown from "showdown";
Vue.use(showdown);
视图
import showdown from "showdown";
let converter = new showdown.Converter();
// 显示表格
converter.setOption("tables",true);

let text= `# hello`;
let htmlText = converter.makeHtml(text);

github-markdown-css

用于修饰经过处理的 markdown内容,尽管我们对内容进行了处理,但有些内容是没办法通过设置标签进行展示的,比如说引入,原生的html没有这种样式。通过引入github-markdown-css,我们可以正常的显示引入的样式。

引入:npm install github-markdown-css

使用:

<article v-html="" class="markdown-body"></article>
<script>
import "../node_modules/github-markdown-css/github-markdown.css"
</script>

highlight.js

用于渲染代码

引入:npm install highlight

使用:

main.js

import hljs from "highlight.js";
import "highlight.js/styles/default.css";

// 代码高亮
Vue.directive("highlight"function(el){
let blocks = el.querySelectorAll("pre code");
blocks.forEach((block)=>{
hljs.highlightBlock(block);
})
})

完整代码示例

<template>
<div>
<article v-html="htmlText" class="markdown-body"></article>

<article v-html="htmlCode" v-highlight class="markdown-body"></article>
</div>
</template>
<script>
import "/node_modules/github-markdown-css/github-markdown.css"
import showdown from 'showdown';
let converter = new showdown.Converter();
// 显示表格
converter.setOption("tables",true);

export default {
name: "Home",
data(){
return{
htmlText: '',
htmlCode: ''
}
},
mounted(){
this.test();
},
methods: {
test(){
let text= `# hello`;
let htmlText = converter.makeHtml(text);
this.htmlText = htmlText;

let code = `
public void main(){
System.out.println();
}`;
this.htmlCode=converter.makeHtml(code);

}
}
}
</script>
<style scoped>
</style>