所需插件:marked、highlight、uViewUI;
- 将markdown文本用
marked
插件解析为html(小程序富文本),再用uView
富文本显示出来;
- 新建uni项目,安装
uView
; - 使用npm安装
marked
:
npm install marked
- 使用npm安装
highlight
,给代码块添加主题:
npm install highlight.js
- vue代码如下:
<template>
<view>
<u-parse :html="content" :tag-style="parse_style" selectable></u-parse>
</view>
</template>
<script>
const {
marked
} = require('marked');
import hljs from "highlight.js";
import "highlight.js/scss/atom-one-dark.scss";
export default {
onLoad(e) {
this.initHighLight();
this.content = marked(" ``` console.log('log'); ``` ");
},
data() {
return {
content: "",
parse_style: {
// 字符串的形式
h1: 'padding:20rpx 0;',
h2: 'padding:10rpx 0;',
h3: 'padding:10rpx 0;',
h4: 'padding:10rpx 0;',
h5: 'padding:5rpx 0;',
h6: 'padding:5rpx 0;',
ul: 'margin-bottom:20rpx;padding-left:30rpx;',
ol: 'margin-bottom:20rpx;padding-left:30rpx;',
// #ifdef MP-WEIXIN
code: 'color: #ccc;background-color: #2d2d2d;margin: 0 5rpx;padding: 6rpx 8rpx;border-radius: 6rpx;text-align:center;',
// #endif
// #ifdef H5
code: 'color: #c7254e;background-color: #f9f2f4;margin: 0 5rpx;padding: 6rpx 8rpx;border-radius: 6rpx;text-align:center;',
// #endif
pre: 'white-space: pre;overflow: auto;background: #2d2d2d;border-radius: 4rpx;border: none;color: #ccc;margin-bottom: 20rpx;padding:20rpx;',
'pre code': 'margin:0;padding:0;background: none;color: #ccc;',
blockquote: 'padding: 15rpx;margin:0 0 20rpx 0;border-radius: 6rpx;',
p: 'margin-bottom:20rpx',
table: 'width:100%;margin-bottom:20rpx;border-collapse: collapse;',
th: 'background-color: whitesmoke;border: 1px solid #e6e6e6;padding:10rpx;',
td: 'border: 1px solid #e6e6e6;padding:10rpx;',
}
}
},
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>
<style lang="scss">
page {
background-color: #f4f6f8;
}
</style>
- 通过initHighLight将marked高亮配置出来,再解析为html格式使用;
- 使用uView的
u-parse
组件,parse_style
为用户自定义样式配置; import "highlight.js/scss/atom-one-dark.scss";
可根据highlight.js/scss/下文件调整皮肤;