最近項目裏須要用到富文本編輯器,同事選擇裏百度出的ueditor,可是裏面自帶的圖片上傳功能須要後臺配合,配置成服務器地址,和咱們實際狀況不是太符合,因而另想辦法,搞定圖片上傳。css
首先重寫裏toolbars配置。最重要的是要把原先的上傳圖片功能按鈕去掉,下面是我用到的配置項vue
toolbars: [
[
"fullscreen",
"source",
"undo",
"redo",
"bold",
"italic",
"underline",
"fontborder",
"strikethrough",
"superscript",
"subscript",
"removeformat",
"formatmatch",
"autotypeset",
"blockquote",
"pasteplain",
"|",
"forecolor",
"backcolor",
"insertorderedlist",
"insertunorderedlist",
"selectall",
"cleardoc",
"mergeright", //右合併單元格
"mergedown", //下合併單元格
"deleterow", //刪除行
"deletecol", //刪除列
"splittorows", //拆分紅行
"splittocols", //拆分紅列
"splittocells", //徹底拆分單元格
"deletecaption", //刪除表格標題
"inserttitle", //插入標題
"mergecells", //合併多個單元格
"deletetable", //刪除表格
"cleardoc", //清空文檔
"insertparagraphbeforetable", //"表格前插入行"
"fontfamily", //字體
"fontsize", //字號
"paragraph", //段落格式
"inserttable", //插入表格
"edittable", //表格屬性
"edittd", //單元格屬性
"link" //超連接
]
]
複製代碼
更多配置可參考官網bash
初始化ueditor的時候觸發一個方法,由於個人項目是用vue寫的,並且封裝了一層ueditor,因此就對外暴露了一個beforeInit方法。服務器
<fw-ueditor-wrap
v-model="mainBody"
:config="myConfig"
@beforeInit="addCustomDialog"
:key="1"
></fw-ueditor-wrap>
複製代碼
// 添加自定義彈窗
addCustomDialog(editorId) {
let that = this;
window.UE.registerUI(
"test-dialog",
function(editor, uiName) {
// 參考http://ueditor.baidu.com/doc/#COMMAND.LIST
var btn = new window.UE.ui.Button({
name: "dialog-button",
title: "上傳圖片",
cssRules: `background-image: url('/image/upload.png') !important;background-size: cover;`,
onclick: function() {
// 渲染dialog
that.dialogVisible = true;
editor.execCommand(uiName);
}
});
return btn;
},
100 /* 指定添加到工具欄上的那個位置,默認時追加到最後 */,
editorId /* 指定這個UI是哪一個編輯器實例上的,默認是頁面上全部的編輯器都會添加這個按鈕 */
);
}
複製代碼
其實就是在toolbar工具欄後面又加了一個自定義的按鈕,實現上傳功能。編輯器
彈窗我用的是element的彈窗,使用方式參考element官網彈窗。而且使用了element的upload上傳組件工具
<el-dialog
title="上傳圖片"
v-if="dialogVisible"
:visible.sync="dialogVisible"
width="30%"
>
<el-upload
class="upload-demo"
drag
accept=".png, .jpg"
:headers="headers"
:action="uploadAddr"
:beforeUpload="beforeAvatarUpload"
:on-success="uploadImageSuccess"
:on-error="uploadImageError"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
將文件拖到此處,或
<em>點擊上傳</em>
</div>
<div class="el-upload__tip" slot="tip">
只能上傳jpg/png文件,且不超過5M
</div>
</el-upload>
</el-dialog>
複製代碼
關鍵的就是上傳成功後須要觸發uploadFile方法,將上傳成功的圖片插入到富文本編輯器中字體
uploadFile(file) {
//關鍵
let editor = document.querySelector(".edui-default").getAttribute("id");
window.UE.getEditor(editor).execCommand("insertimage", {
src: file.url,
width: "100",
height: "100"
});
this.dialogVisible = false;
},
// eslint-disable-next-line no-unused-vars
uploadImageSuccess(response, file, fileList) {
if (response) {
this.$message({
message: "上傳成功",
type: "success"
});
let fileObj = {
name: response.originalName,
url: response.url
};
// this.fileList.push(fileObj);
this.uploadFile(fileObj);
} else {
this.$message({
message: "上傳失敗",
type: "warning"
});
}
}
複製代碼
大功告成,搞定!ui