Markdown富文本编辑器(Vue),含图片上传
- 富文本有很多款,但我用的比较好的还是这款Markdown编辑器,因为Markdown存在语法支持,以及上传图片自带的函数调用支持,可以快速高效的编辑,有一点是要解析成html需要marked插件。
(CSDN博客也支持这款编辑器,CSDN中的图片上传好像是单个上传的,这样的话可以在CSDN中进行编辑后直接复制往自己的编辑器,来达到将图片托管于CSND免去了上传图片的步骤)
步骤:下载mavon-editor插件和marked(解析成html)——> 导入mavonEditor组件 ——> 绑定对应事件以及model ——> 进行事件处理
(这边用到统一上传)
- npm install mavon-editor -save
- npm install marked -save
- marked.js 将 markdown 转换成 html (change事件的第二个参数也可以获取到转化后的html)
- highlightj.js 代码高亮
- highlightjs-line-numbers.js 代码行号
<template>
<div id="editor">
<!--:ishljs为高亮-->
<!--:v-model获取到编辑的 Markdown代码,需要用marked解析成html-->
<!--change为更改事件,一更改触发-->
<!--imgAdd为添加图片调用的函数-->
<!--imgDel为删除图片调用的函数-->
<mavon-editor
ref="md"
style="height: 100%"
:ishljs="true"
v-model="mavonValue"
@change="chang"
@imgAdd="imgAdd"
@imgDel="imgDel"
></mavon-editor>
<button @click="uploadImg">统一上传图片</button>
</div>
</template>
<script>
// 导入对应组件以及样式表
import { mavonEditor } from "mavon-editor";
import "mavon-editor/dist/css/index.css";
//将markdown语法解析成html的插件
import marked from "marked";
export default {
name: "editor",
components: {
mavonEditor
// 或 'mavon-editor': mavonEditor
},
data() {
return {
mavonValue: "",
markedValue:'',
imgList: []
};
},
methods: {
//第一个参数为为解码的markdown语法代码,第二个参数为解码后的html代码
chang: function (val,render) {
//解析成html
console.log(marked(this.mavonValue));
this.markedValue=marked(this.mavonValue)
//console.log(this.markedValue);
},
// 绑定@imgAdd event
imgAdd(pos, file) {
// 缓存图片信息(当前还是本地图片状态)
this.imgList[pos] = file;
// console.log(pos)
console.log("添加图片:" + this.imgList[pos]);
},
imgDel(pos) {
delete this.imgList[pos];
console.log("删除图片:" + this.imgList[pos]);
},
uploadImg() {
// 第一步.将图片上传到服务器(一次性上传).
for (var i in this.imgList) {
console.log("上传图片" + this.imgList[i]);
//接口提供了一种表示表单数据的键值对的构造方式,经过它的数据可以使用
//multipart/form-data
var formdata = new FormData();
formdata.append("file", this.imgList[i]);
this.$axios({
url: "上传图片的后台地址",
method: "post",
data: formdata,
headers: { "Content-Type": "multipart/form-data" }
}).then(res => {
// 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)
/**
* $vm 指为mavonEditor实例,可以通过如下两种方式获取
* 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后,`$vm`为`mavonEditor`
* 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>,`$vm`为 `this.$refs.md`
*/
console.log(res);
//pos为在编辑框中对应的位置0。。。,第二个为上传后的url
this.$refs.md.$img2Url(pos,url)
});
}
}
}
};
</script>
<style>
#editor {
margin: auto;
width: 80%;
height: 580px;
}
</style>
!!!提取到代码后在要显示的页面中引入样式,并在显示的div加上class="markdown-body"(不然有些没效果)
//导入对应样式表
import 'mavon-editor/dist/css/index.css';
//要显示的div设置类
<div class="markdown-body" v-html="markdown_code"/>