<script src="wangEditor/3.1.1/wangEditor.min.js"></script>
Vue.component('my-wangeditor', {
props: ['value'],
data() {
return {
flag: true,
editor: null,
}
},
watch: {
value(val) {
if(this.flag){
//這里初始化的時候賦值
this.editor.txt.html(val);
}
this.flag = true;
}
},
mounted: function () {
const self = this;
let E = window.wangEditor;
self.editor = new E(this.$refs.editorElem); //創建富文本實例
self.editor.customConfig.onchange = (html) => {
this.flag = false;//這里改變絕對不能觸發初始化賦值 否者會出現問題
self.$emit('input', html);
};
self.editor.customConfig.uploadImgServer = '圖片上傳地址';
self.editor.customConfig.uploadFileName = 'file';
self.editor.customConfig.uploadImgMaxSize = 1024 * 1024;// 將圖片大小限制為 1M
self.editor.customConfig.uploadImgMaxLength = 1;// 限制一次最多上傳 1 張圖片
self.editor.customConfig.uploadImgTimeout = 3 * 60 * 1000;// 設置超時時間
// editor.customConfig.uploadImgHeaders = {
// 'Accept': '*/*',
// 'Authorization':'Bearer ' + token //頭部token
// };
self.editor.customConfig.menus = [ //菜單配置
'head', // 標題
'bold', // 粗體
'fontSize', // 字號
'fontName', // 字體
'italic', // 斜體
'underline', // 下划線
'strikeThrough', // 刪除線
'foreColor', // 文字顏色
'backColor', // 背景顏色
'link', // 插入鏈接
'list', // 列表
'justify', // 對齊方式
'quote', // 引用
'emoticon', // 表情
'image', // 插入圖片
'table', // 表格
'video', // 插入視頻
// 'code', // 插入代碼
'undo', // 撤銷
'redo' // 重復
];
//下面是最重要的的方法
self.editor.customConfig.uploadImgHooks = {
before: function (xhr, editor, files) {
// 圖片上傳之前觸發
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,files 是選擇的圖片文件
// 如果返回的結果是 {prevent: true, msg: 'xxxx'} 則表示用戶放棄上傳
// return {
// prevent: true,
// msg: '放棄上傳'
// }
},
success: function (xhr, editor, result) {
// 圖片上傳並返回結果,圖片插入成功之后觸發
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,result 是服務器端返回的結果
self.imgUrl = Object.values(result.data).toString()
},
fail: function (xhr, editor, result) {
// 圖片上傳並返回結果,但圖片插入錯誤時觸發
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,result 是服務器端返回的結果
},
error: function (xhr, editor) {
// 圖片上傳出錯時觸發
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象
},
timeout: function (xhr, editor) {
// 圖片上傳超時時觸發
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象
},
// 如果服務器端返回的不是 {errno:0, data: [...]} 這種格式,可使用該配置
// (但是,服務器端返回的必須是一個 JSON 格式字符串!!!否則會報錯)
customInsert: function (insertImg, result, editor) {
// 圖片上傳並返回結果,自定義插入圖片的事件(而不是編輯器自動插入圖片!!!)
// insertImg 是插入圖片的函數,editor 是編輯器對象,result 是服務器端返回的結果
// 舉例:假如上傳圖片成功后,服務器端返回的是 {url:'....'} 這種格式,即可這樣插入圖片:
// let url = Object.values(result.data); //result.data就是服務器返回的圖片名字和鏈接
// JSON.stringify(url); //在這里轉成JSON格式
insertImg(result.data.location);
// result 必須是一個 JSON 格式字符串!!!否則報錯
}
};
self.editor.create();
},
methods: {
},
updated() {
},
created() {
},
destroyed() {
},
template: '<div id="wangeditor"><div ref="editorElem" v-model="value" style="text-align:left"></div></div>'
});
使用方法
<my-wangeditor v-model="notes"></my-wangeditor>