最近開發vue項目過程中,由於產品需要在項目中添加富文本編輯器,也在npm上找了幾個基於vue開發的富文本編輯器,但是對兼容性比較高,不能兼容到IE9,10。所以最後決定使用百度UEditor。然後又是各種找如何集成到vue中。好記性不如爛筆頭,記錄下來以便以後需要的時候可以直接用。
1.首先下載UEditor源碼,將整個文件放到static文件夾中
2.然後將UEditor集成到項目中去。
找到src/main.js,在main.js中
import '../static/ueditor/ueditor.config.js'
import '../static/ueditor/ueditor.all.min.js'
import '../static/ueditor/lang/zh-cn/zh-cn.js'
import '../static/ueditor/ueditor.parse.min.js'
3.在src/components文件夾下創建公共組件UE.vue文件,作爲編輯器組件
<template>
<div class="UE">
<!--這個地方的大小是可以自己控制的-->
<div id="editor" style="width:100%;height:120px;">
</div>
</div>
</template>
export default {
name:'ue',
props:{
value:{
type:String,
default:""
}
},
data() {
return {
editor: null,
};
},
mounted() {
// 實例化editor編輯器
this.editor = window.UE.getEditor("editor");
//設置編輯器默認內容
this.editor.addListener('ready', () => {
this.editor.setContent(this.value)
})
},
methods: {
//獲取編輯器中的內容
getUEContent () {
return this.editor.getContent()
}
},
destroyed() {
// 將editor進行銷燬
this.editor.destroy();
}
}
4.我們可以通過ueditor.config.js來改變編輯器所顯示的選項
如果我們默認顯示的話,會是這個樣子
如果你不需要某些元素,你可以在ueditor.config.js中的toolbars中設置需要顯示的標籤
當然你還需要做下其他的配置,比如指定編輯器資源文件根目錄
window.UEDITOR_HOME_URL = "./static/UE/";
在這裏友情提示,如果你的項目打包之後不是放在一級目錄下,建議寫成這樣相對路徑,不然會報錯找不到資源。
5.這樣你就可以在其他組件引入使用了,我們可以通過props向編輯器傳遞默認顯示的值,還可以通過getUEContent()方法獲取編輯器輸入的內容。但是在瀏覽器控制檯你還是會看到報錯
後臺配置項返回格式出錯,上傳功能將不能正常使用!
這是因爲我們在編輯器中上傳圖片或者視頻的時候,沒有配置服務器請求接口,在ueditor.config.js中,對serverUrl進行配置就可以了
serverUrl: "" //這個接口地址去跟你們的後臺要就可以了
到這裏,我們就可以愉快的使用UEditor富文本編輯器了