1. 程式人生 > >Vue.js結合Ueditor

Vue.js結合Ueditor

前一段時間公司Vue.js專案需要使用UEditor富文字編輯器,在百度上搜索一圈沒有發現詳細的說明,決定自己嘗試,忙活了一天終於搞定了。

1. 總體思路

1.1 模組化

vue的很大的一個優勢在於模組化,我們可以通過模組化實現頁面和邏輯的複用。所以可以把Ueditor重新封裝成一個.vue的模板檔案。其他元件通過引入這個模板實現程式碼複用。

1.2 資料傳輸

首先父元件需要設定編輯器的長度、寬度、初始文字,這些資料可以通過props來傳遞。編輯器中的文字變化可以通過vue自定義事件向父元件傳遞。

2. 具體實現步驟

2.1 引入關鍵的JS以及CSS檔案

將以下檔案全部拷貝到專案中
這裡寫圖片描述

2.2 配置Ueditor.config.js

首先配置URL引數,我們需要將這個路徑指向剛才拷貝的檔案的更目錄,注意這裡最好使用相對路勁。

var URL = window.UEDITOR_HOME_URL || '/static/ueditor/';

然後是預設寬度高度的設定

,initialFrameWidth:null  // null表示寬度自動
,initialFrameHeight:320

其他功能的配置可以在官方文件檢視

2.3 建立編輯器模板

我們需要在編輯器模板中import Ueditor核心JS庫,並新增contentChange回撥函式就大功告成了。

之所以使用import語法來引入核心JS庫是因為這樣更符合ES6模組化的規範,我看到網上有人建議在main.js中引入JS,但是過早地引入JS可能導致頁面首次載入緩慢。

<template>
  <div ref="editor"></div>
</template>

<script>
  /* eslint-disable */
  import '../../../assets/js/ueditor/ueditor.config';
  import '../../../assets/js/ueditor/ueditor.all';
  import '../../../assets/js/ueditor/lang/zh-cn/zh-cn'
; import { generateRandonInteger } from '../../../vuex/utils'; export default { data() { return { id: generateRandonInteger(100000) + 'ueditorId', }; }, props: { value: { type: String, default: null, }, config: { type: Object, default: {}, } }, watch: { value: function value(val, oldVal) { this.editor = UE.getEditor(this.id, this.config); if (val !== null) { this.editor.setContent(val); } }, }, mounted() { this.$nextTick(function f1() { // 保證 this.$el 已經插入文件 this.$refs.editor.id = this.id; this.editor = UE.getEditor(this.id, this.config); this.editor.ready(function f2() { this.editor.setContent(this.value); this.editor.addListener("contentChange", function () { const wordCount = this.editor.getContentLength(true); const content = this.editor.getContent(); const plainTxt = this.editor.getPlainTxt(); this.$emit('input', { wordCount: wordCount, content: content, plainTxt: plainTxt }); }.bind(this)); this.$emit('ready', this.editor); }.bind(this)); }); }, };
</script> <style> body{ background-color:#ff0000; } </style>

3. 編輯器的使用

使用編輯器模板的時候我需要通過props傳入config以及初始文字value。

<template xmlns:v-on="http://www.w3.org/1999/xhtml">
    <div class="edit-area">
      <ueditor v-bind:value=defaultMsg v-bind:config=config v-on:input="input" v-on:ready="ready"></ueditor>
    </div>

</template>

<script>
  import ueditor from './ueditor.vue';

  export default {
    components: {
      ueditor,
    },
    data() {
      return {
        defaultMsg: '初始文字',  
        config: {
          initialFrameWidth: null,
          initialFrameHeight: 320,
        },
      };
    },
  };
</script>


----------
如果需要讓Ueditor上傳圖片的話,還需要在後臺配置一個介面。這部分還沒有時間研究,等過幾天補上。