在做个人博客的时候找了一些富文本编辑器来使用,虽然说有一些bug,但是用起来感觉很舒服,最后还是打算用mavon-editor。遇到比较麻烦的一个问题就是:如果内容中有图片的话,二次回现编辑的时候工具栏里的图片控制列表是无法实时同步的,这样就无法对已有图片进行删除。
在查看了插件代码后,发现可以用以下方式实现。
<mavon-editor ref=md class="mavonEditor" v-model="content" @imgAdd="imgAdd" @imgDel="imgDel" @save="saveMavonEditor"></mavon-editor>
1、首先要存储md格式(可以获取到两种格式的内容一种是md格式,一种html格式)
console.log('html格式',this.$refs.md.d_render)
console.log('md格式',this.$refs.md.d_value)
![在这里插入图片描述](https://img-blog.csdnimg.cn/7c9636bd8f1540a488f36d28648e9682.png
2、解析md格式中的图片名称和图片路径并取出,然后通过方法添加到图片控制列表
mounted() {
//将解析到图片名字和地址添加到控制列表(具体为什么要填这些参数,是因为mavon-editor插件中要使用到这些内容)
let imgRecurrent =(name,url)=>{
this.$refs.md.$refs.toolbar_left.$imgAddByFilename(
//markdown模板图片地址
url,
{
// 图片控制列表图片链接
miniurl:url,
// 图片控制列表名字
name:name,
//markdown模板图片名称
_name:name
}
)
}
// 查找模板中已存在图片的名字和地址,返回的格式为[{text:'xxx',url: 'xxx.png'}]
let findImg = (str)=>{
const regex = /!\[(.*?)\]\((.*?)\)/g;
const matches = [];
let match;
while ((match = regex.exec(str)) !== null) {
const [, text, url] = match;
matches.push({ text, url });
}
return matches
}
//本人自己写的获取模板内容的接口,内容就在步骤一
post_not_saved().then(res=>{
this.title = res.data.title;
this.content = res.data.content;
let imgData = findImg(this.content);
imgData.forEach(item=>{
imgRecurrent(item.text,item.url)
})
})
}
结果就是下图