把wangeditor作為組件的形式使用
子組件中
<template>
<div id="wangeditor">
<div ref="editorElem" style="text-align:left"></div>
</div>
</template>
<script>
import E from 'wangeditor'
export default {
name: 'editorElem',
data () {
return {
editorContent: '',
}
},
props:['catchData'], //接收父組件的方法
mounted() {
var editor = new E(this.$refs.editorElem) //創(chuàng)建富文本實(shí)例
editor.customConfig.onchange = (html) => {
this.editorContent = html
this.catchData(html) //把這個(gè)html通過(guò)catchData的方法傳入父組件
}
editor.customConfig.uploadImgServer = '你的上傳圖片的接口'
editor.customConfig.uploadFileName = '你自定義的文件名'
editor.customConfig.uploadImgHeaders = {
'Accept': '*/*',
'Authorization':'Bearer ' + token //頭部token
}
editor.customConfig.menus = [ //菜單配置
'head',
'list', // 列表
'justify', // 對(duì)齊方式
'bold',
'fontSize', // 字號(hào)
'italic',
'underline',
'image', // 插入圖片
'foreColor', // 文字顏色
'undo', // 撤銷
'redo', // 重復(fù)
]
//下面是最重要的的方法
editor.customConfig.uploadImgHooks = {
before: function (xhr, editor, files) {
// 圖片上傳之前觸發(fā)
// xhr 是 XMLHttpRequst 對(duì)象,editor 是編輯器對(duì)象谒获,files 是選擇的圖片文件
// 如果返回的結(jié)果是 {prevent: true, msg: 'xxxx'} 則表示用戶放棄上傳
// return {
// prevent: true,
// msg: '放棄上傳'
// }
},
success: function (xhr, editor, result) {
// 圖片上傳并返回結(jié)果易遣,圖片插入成功之后觸發(fā)
// xhr 是 XMLHttpRequst 對(duì)象焚志,editor 是編輯器對(duì)象,result 是服務(wù)器端返回的結(jié)果
this.imgUrl=Object.values(result.data).toString()
},
fail: function (xhr, editor, result) {
// 圖片上傳并返回結(jié)果,但圖片插入錯(cuò)誤時(shí)觸發(fā)
// xhr 是 XMLHttpRequst 對(duì)象宿饱,editor 是編輯器對(duì)象胀瞪,result 是服務(wù)器端返回的結(jié)果
},
error: function (xhr, editor) {
// 圖片上傳出錯(cuò)時(shí)觸發(fā)
// xhr 是 XMLHttpRequst 對(duì)象针余,editor 是編輯器對(duì)象
},
timeout: function (xhr, editor) {
// 圖片上傳超時(shí)時(shí)觸發(fā)
// xhr 是 XMLHttpRequst 對(duì)象,editor 是編輯器對(duì)象
},
// 如果服務(wù)器端返回的不是 {errno:0, data: [...]} 這種格式凄诞,可使用該配置
// (但是圆雁,服務(wù)器端返回的必須是一個(gè) JSON 格式字符串!7伪朽!否則會(huì)報(bào)錯(cuò))
customInsert: function (insertImg, result, editor) {
// 圖片上傳并返回結(jié)果,自定義插入圖片的事件(而不是編輯器自動(dòng)插入圖片Q打A忆獭!)
// insertImg 是插入圖片的函數(shù)窖剑,editor 是編輯器對(duì)象坚洽,result 是服務(wù)器端返回的結(jié)果
// 舉例:假如上傳圖片成功后,服務(wù)器端返回的是 {url:'....'} 這種格式西土,即可這樣插入圖片:
let url = Object.values(result.data) //result.data就是服務(wù)器返回的圖片名字和鏈接
JSON.stringify(url) //在這里轉(zhuǎn)成JSON格式
insertImg(url)
// result 必須是一個(gè) JSON 格式字符串Q冉ⅰ!!否則報(bào)錯(cuò)
}
}
editor.create()
},
父組件中
<template>
<div id="father">
<wangeditor :catchData="catchData"></wangeditor>
</div>
</template>
<script>
import wangeditor from './wangeditor'
data(){
return{
content:""
}
},
methods:{
catchData(value){
this.content=value //在這里接受子組件傳過(guò)來(lái)的參數(shù)跳昼,賦值給data里的參數(shù)
}
},
components: {
wangeditor
},
</script>
上面字最多的地方好好看清楚般甲,只有做了customInsert: function (insertImg, result, editor){}里的步驟,圖片才會(huì)在富文本中顯示鹅颊,否則是不會(huì)自動(dòng)顯示敷存。