Markdown富文本編輯器(Vue),含圖片上傳
- 富文本有很多款,但我用的比較好的還是這款Markdown編輯器,因?yàn)镸arkdown存在語法支持,以及上傳圖片自帶的函數(shù)調(diào)用支持,可以快速高效的編輯,有一點(diǎn)是要解析成html需要marked插件。
(CSDN博客也支持這款編輯器,CSDN中的圖片上傳好像是單個上傳的,這樣的話可以在CSDN中進(jìn)行編輯后直接復(fù)制往自己的編輯器,來達(dá)到將圖片托管于CSND免去了上傳圖片的步驟)
步驟:下載mavon-editor插件和marked(解析成html)——> 導(dǎo)入mavonEditor組件 ——> 綁定對應(yīng)事件以及model ——> 進(jìn)行事件處理
(這邊用到統(tǒng)一上傳)
- npm install mavon-editor -save
- npm install marked -save
- marked.js 將 markdown 轉(zhuǎn)換成 html (change事件的第二個參數(shù)也可以獲取到轉(zhuǎn)化后的html)
- highlightj.js 代碼高亮
- highlightjs-line-numbers.js 代碼行號
<template>
<div id="editor">
<!--:ishljs為高亮-->
<!--:v-model獲取到編輯的 Markdown代碼,需要用marked解析成html-->
<!--change為更改事件,一更改觸發(fā)-->
<!--imgAdd為添加圖片調(diào)用的函數(shù)-->
<!--imgDel為刪除圖片調(diào)用的函數(shù)-->
<mavon-editor
ref="md"
style="height: 100%"
:ishljs="true"
v-model="mavonValue"
@change="chang"
@imgAdd="imgAdd"
@imgDel="imgDel"
></mavon-editor>
<button @click="uploadImg">統(tǒng)一上傳圖片</button>
</div>
</template>
<script>
// 導(dǎo)入對應(yīng)組件以及樣式表
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: {
//第一個參數(shù)為為解碼的markdown語法代碼,第二個參數(shù)為解碼后的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) {
// 緩存圖片信息(當(dāng)前還是本地圖片狀態(tài))
this.imgList[pos] = file;
// console.log(pos)
console.log("添加圖片:" + this.imgList[pos]);
},
imgDel(pos) {
delete this.imgList[pos];
console.log("刪除圖片:" + this.imgList[pos]);
},
uploadImg() {
// 第一步.將圖片上傳到服務(wù)器(一次性上傳).
for (var i in this.imgList) {
console.log("上傳圖片" + this.imgList[i]);
//接口提供了一種表示表單數(shù)據(jù)的鍵值對的構(gòu)造方式,經(jīng)過它的數(shù)據(jù)可以使用
//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替換到文本原位置 -> 
/**
* $vm 指為mavonEditor實(shí)例,可以通過如下兩種方式獲取
* 1. 通過引入對象獲取: `import {mavonEditor} from ...` 等方式引入后,`$vm`為`mavonEditor`
* 2. 通過$refs獲取: html聲明ref : `<mavon-editor ref=md ></mavon-editor>,`$vm`為 `this.$refs.md`
*/
console.log(res);
//pos為在編輯框中對應(yīng)的位置0。。。,第二個為上傳后的url
this.$refs.md.$img2Url(pos,url)
});
}
}
}
};
</script>
<style>
#editor {
margin: auto;
width: 80%;
height: 580px;
}
</style>
?。。√崛〉酱a后在要顯示的頁面中引入樣式,并在顯示的div加上class="markdown-body"(不然有些沒效果)
//導(dǎo)入對應(yīng)樣式表
import 'mavon-editor/dist/css/index.css';
//要顯示的div設(shè)置類
<div class="markdown-body" v-html="markdown_code"/>