mavonEditor
是一款基于vue的markdown编辑器,比较适合博客系统,使用方法简单,网上都有教程,基本没坑。
下载并且 main.js引入 mavonEditor
npm install mavon-editor --save//引入import mavonEditor from 'mavon-editor'import 'mavon-editor/dist/css/index.css'// useVue.use(mavonEditor)
html:
<mavon-editor v-model="content" ref="md" @change="change" @imgAdd="imgAdd" style="min-height: 600px" :toolbars= 'toolbars'/>//toolbars 省略也可以
data:
toolbars: { bold: true, // 粗体 italic: true, // 斜体 header: true, // 标题 underline: true, // 下划线 strikethrough: true, // 中划线 mark: true, // 标记 superscript: true, // 上角标 subscript: true, // 下角标 quote: true, // 引用 ol: true, // 有序列表 ul: true, // 无序列表 link: true, // 链接 imagelink: true, // 图片链接 code: true, // code table: true, // 表格 fullscreen: false, // 全屏编辑 readmodel: false, // 沉浸式阅读 htmlcode: true, // 展示html源码 help: true, // 帮助 /* 1.3.5 */ undo: true, // 上一步 redo: true, // 下一步 trash: true, // 清空 save: false, // 保存(触发events中的save事件) /* 1.4.2 */ navigation: true, // 导航目录 /* 2.1.8 */ alignleft: true, // 左对齐 aligncenter: true, // 居中 alignright: true, // 右对齐 /* 2.2.1 */ subfield: true, // 单双栏模式 preview: false // 预览 }
代码高亮:
下载highlight并在 main.js 引入
import hljs from 'highlight.js' //导入代码高亮文件import 'highlight.js/styles/googlecode.css
网上教程:(注册一个全局指令)
Vue.directive('highlight',function (el) { let highlight = el.querySelectorAll('code,pre'); highlight.forEach((block)=>{ if(block){ hljs.highlightBlock(block); } }) })//使用指令<mavon-editor v-highlight ....>
以上方法确实可行但是代码过多或者刷新后有问题(代码高亮则不生效),查看控制台发现hljs未定义报错
解决方案(不使用指令,判断hljs可用时再进行代码高亮操作):
在获取到内容后执行以下方法:
function highlighthandle(){ let highlight = document.querySelectorAll('code,pre'); highlight.forEach((block)=>{ hljs.highlightBlock(block); })}function getHljs(){ // 判断hljs是否可用 return new Promise((resolve,reject)=>{ function hljsTrue(){ try{ if(hljs){ clearTimeout(Timer); Timer = null; resolve(); } }catch(e){ Timer = setTimeout(()=>{ hljsTrue(); },100) } } hljsTrue(); })}getHljs().then(()=>{ highlighthandle()})