1. 程式人生 > >vue2.x整合百度UEditor富文字編輯器方法

vue2.x整合百度UEditor富文字編輯器方法

最近開發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富文字編輯器了