在vue的’項目中遇到了須要使用富文本編輯器的需求,在github上看了不少vue封裝的editor插件,不少對圖片上傳和視頻上傳的支持並非很好,最終仍是決定使用UEditor。javascript
這類的文章網上有不少,我進行了摸索、手寫代碼、彙總、排版,造成了這篇文章。html
首先,去官網上下載UEditor的源碼,根據你後臺語言的不一樣下載對應的版本(PHP、Asp、.Net、Jsp),下載地址。vue
下載以後,把資源放到 /static/ue/
靜態目錄下。文檔結構以下:
java
(我把UEditor放到了static
靜態目錄下面,這裏的文件不會被webpack
打包,固然你也能夠選擇性地放進src中)webpack
咱們打開 ueditor.config.js
,修改其中的window.UEDITOR_HOME_UR
配置,以下:git
window.UEDITOR_HOME_URL = "/static/UE/"; //指定編輯器資源文件根目錄 var URL = window.UEDITOR_HOME_URL || getUEBasePath();
ueditor.config.js
文件有不少配置,能夠在這裏進行一些初始化的全局配置,好比編輯器的默認寬高等:github
,initialFrameWidth:1000 //初始化編輯器寬度,默認1000 ,initialFrameHeight:320 //初始化編輯器高度,默認320
其餘的參數配置,在該文件中有詳細列出,或者參考官方文檔 http://fex.baidu.com/ueditor/web
打開 /src/main.js 文件,插入下面的代碼:後端
//ueditor import '../static/UE/ueditor.config.js' import '../static/UE/ueditor.all.min.js' import '../static/UE/lang/zh-cn/zh-cn.js' import '../static/UE/ueditor.parse.min.js'
咱們在 /src/components/
目錄下建立 UE.vue
文件,做爲咱們的編輯器組件文件。
下面代碼提供簡單功能,具體使用根據需求完善該組件便可。服務器
<template> <div> <script id="editor" type="text/plain"></script> </div> </template> <script> export default { name: 'ue', data () { return { editor: null } }, props: { value: '', config: {} }, mounted () { this.editor = window.UE.getEditor('editor', this.config); this.editor.addListener('ready', () => { this.editor.setContent(this.value) }) }, methods: { getUEContent () { return this.editor.getContent() } }, destroyed () { this.editor.destroy() } } </script>
組件暴露了兩個接口:
value
是編輯器的文字
config
是編輯器的配置參數
簡單地建立一個須要UEditor的頁面,再該頁面中使用剛纔封裝好的UE.vue組件:
<template> <div> <Uediter :value="ueditor.value" :config="ueditor.config" ref="ue"></Uediter> <button @click="returnContent">顯示編輯器內容</el-button> <div>{{dat.content}}</div> </div> </template> <script> import Uediter from '@/components/UE.vue'; export default { data () { return { dat: { content: '' }, ueditor: { value: '編輯器默認文字', config: { initialFrameWidth: 800, initialFrameHeight: 320 } } } }, methods: { returnContent () { this.dat.content = this.$refs.ue.getUEContent() } }, components: { Uediter }, } </script>
效果以下:
配置完上述內容後,控制檯可能會出現"後臺配置項返回格式出錯,上傳功能將不能正常使用!"的報錯,
咱們在編輯器中上傳圖片或者視頻,也會出現響應的報錯,這是由於沒有配置服務器的請求接口,在ueditor.config.js中,對serverUrl進行配置:
// 服務器統一請求接口路徑 , serverUrl: 'http://172.16.254.49:83/File/UEditor' //地址管大家後端要去