marked是对markdown进行解析的插件,它可以把markdown语法解析成html语法,从而实现页面效果,而highlight.js是对解析出的代码实现高亮效果
效果:
安装:避免踩我走的坑,安装尽量按照这个版本安装
npm install marked@0 --save
npm install highlight.js@9 --save
代码:index.vue
<template>
<div class="detail">
<div class="markdown-body">
<div class="article_message hljs renderNav" v-html="code"></div>
</div>
</div>
</template>
<script>
import marked from "marked"; // 引入marked
import hljs from "highlight.js"; // 引入 highlight.js
import "highlight.js/styles/monokai-sublime.css"; // 引入高亮样式 这里我用的是sublime样式
export default {
name: "Detail",
data() {
return {
code: "```javascript\nfunction(){\n\tconsole.log(123) //注释\n}\njavascript\nfunction(){\n\tconsole.log(123) //注释\n}\njavascript\nfunction(){\n\tconsole.log(123) //注释\n}\njavascript\nfunction(){\n\tconsole.log(123) //注释\n}\n```", // 要解析的markdown语法的内容
};
},
mounted() {
var rendererMD = new marked.Renderer();
marked.setOptions({
renderer: rendererMD,
highlight: function (code, language) {
const validLanguage = hljs.getLanguage(language)
? language
: "plaintext";
return hljs.highlight(validLanguage, code).value;
},
pedantic: false,
gfm: true,
tables: true,
breaks: false,
sanitize: false,
smartLists: true,
smartypants: false,
xhtml: false,
});
this.code = marked(this.code); // 将markdown内容解析
},
};
</script>