明天给大家分享一个在uniapp我的项目中用到的markdown语法解析插件uaMarkdown。
如下图:编译至H5+小程序+App端成果。
应用markdown-it
和highlight.js
封装组件。
// 引入markdown-it和highlight.js插件import MarkdownIt from '@/plugins/markdown-it.min.js'import hljs from '@/plugins/highlight/highlight.min.js'// import '@/plugins/highlight/github-dark.min.css'import '@/plugins/highlight/atom-one-light.css'import parseHtml from '@/plugins/html-parser.js'
初始markdown组件
const markdown = MarkdownIt({ html: true, highlight: function(str, lang) { let preCode = "" try { preCode = hljs.highlightAuto(str).value } catch (err) { preCode = markdown.utils.escapeHtml(str); } // 自定义行号 const lines = preCode.split(/\n/).slice(0, -1) let html = lines.map((item, index) => { // 去掉空行 if( item == ''){ return '' } return '<li><span class="line-num" data-line="' + (index + 1) + '"></span>' + item +'</li>' }).join('') html = '<ol style="padding: 0px 30px;">' + html + '</ol>' // 代码复制 copyCode.push(str) let htmlCode = `<div class="markdown-wrap">` // #ifndef MP-WEIXIN htmlCode += `<div style="color: #aaa;text-align: right;font-size: 12px;padding:8px;">` htmlCode += `${lang}<a class="copy-btn" code-data-index="${copyCode.length - 1}" style="margin-left: 8px;">复制代码</a>` htmlCode += `</div>` // #endif htmlCode += `<pre class="hljs" style="padding:0 8px;margin-bottom:5px;overflow: auto;border-radius: 5px;"><code>${html}</code></pre>`; htmlCode += '</div>' return htmlCode }})
解析md语法结构
const parseNodes = (value) => { if(!value) return let htmlString = '' if (value.split("```").length % 2) { let msgContent = value if(msgContent[msgContent.length-1] != '\n'){ msgContent += '\n' } htmlString = markdown.render(msgContent) } else { htmlString = markdown.render(msgContent.value) } // #ifndef APP-NVUE return htmlString // #endif // nvue模式下将htmlString转成htmlArray,其余状况rich-text外部转 // 注:本示例我的项目还没应用nvue编译 // #ifdef APP-NVUE return parseHtml(htmlString) // #endif}
疾速应用
- 根底用法
const mdvalue = '### uniapp markdwon'<ua-markdown :source="mdvalue" />
- 禁用行号
<ua-markdown :source="xxx" :showLine="false" />
ua-markdown组件曾经公布插件市场,能够收费下载应用。
https://ext.dcloud.net.cn/plugin?id=13307