1. 使用 npm 下载 mp-html
插件
官方文档: https://jin-yufeng.gitee.io/mp-html/#/overview/quickstart
npm install mp-html
使用方式
<template>
<view>
<mp-html :content="html" />
</view>
</template>
<script>
import mpHtml from "mp-html/dist/uni-app/components/mp-html/mp-html";
export default {
// 不可省略
components: {
mpHtml,
},
data() {
return {
html: "<div>Hello World!</div>",
};
},
};
</script>
2. 使用 npm 下载 marked
插件和 highlight
插件
marked
插件可以和 highlight 插件共用,实现 markdown 中代码块的高亮效果
marked.js 官方文档:https://marked.js.org/
highlight.js 官方文档:https://fenxianglu.cn/highlight.html
npm install marked
npm install highlight.js
完整代码
<template>
<view>
<mp-html :content="html" />
</view>
</template>
<script>
import mpHtml from "mp-html/dist/uni-app/components/mp-html/mp-html";
import { marked } from "marked";
import hljs from "highlight.js";
import "highlight.js/scss/atom-one-dark.scss";
export default {
// 不可省略
components: {
mpHtml,
},
data() {
return {
html: "<div>Hello World!</div>",
markdown: "```javascript\nfunction(){\n\tconsole.log(123)\n}\n```",
};
},
mounted() {
this.initHighLight();
this.html = marked(this.markdown);
// 下面代码是解决代码高亮无效问题
// this.html = marked(this.markdown).replace(/<pre>/g, "<pre class='hljs'>");
},
methods: {
initHighLight() {
hljs.configure({
useBR: true,
tabReplace: " ",
});
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pedantic: false,
highlight: function (code, lang) {
if (lang && hljs.getLanguage(lang)) {
return hljs.highlight(lang, code, true).value;
} else {
return hljs.highlightAuto(code).value;
}
},
});
},
},
};
</script>