Vue中富文本編輯器wangeditor的v-model封裝

以下代碼實(shí)現(xiàn)只配置部分功能,更多功能擴(kuò)展請查閱wangeditor官網(wǎng)

一、下載依賴

注意wangeditor全部是小寫

npm install wangeditor --save

二、實(shí)現(xiàn)過程中遇到的坑

1、當(dāng)一個(gè)頁面中使用到多個(gè)富文本組件時(shí),會(huì)導(dǎo)致組件之間的id或者ref重復(fù),導(dǎo)致渲染錯(cuò)誤。

解決方案:在組件內(nèi)部使用隨機(jī)字符串綁定組件的ref或者id。


2、在父組件中改變v-model綁定的值,富文本內(nèi)容不改變。

解決方案:使用watch進(jìn)行監(jiān)聽value變化,具體看代碼實(shí)現(xiàn)。


3、每次調(diào)用editor.txt.html()方法,富文本中的光標(biāo)就會(huì)出現(xiàn)在文末,導(dǎo)致在編輯富文本中間的內(nèi)容時(shí),出現(xiàn)鬼畜現(xiàn)象。

解決方案:不要在editor.customConfig.onchange()中調(diào)用editor.txt.html()方法,而使用組件內(nèi)部的一個(gè)content變量進(jìn)行儲(chǔ)存。然后watch content觸發(fā)input事件,改變父組件的邦定值

三、完整代碼實(shí)現(xiàn)

<template>
  <div>
    <div :ref="toolId" class="toolbar"></div>
    <div :ref="editorId" class="text"> <!--可使用 min-height 實(shí)現(xiàn)編輯區(qū)域自動(dòng)增加高度-->
    </div>
  </div>
</template>

<script>
import wangEditor from 'wangeditor'

export default {
  name: 'rich-text',
  props: {
    value: String
  },
  data() {
    return {
      content: '',
      editor: {},
      toolId: '',
      editorId: ''
    }
  },
  computed: {

  },
  watch: {
    value(val) {
      if (val) {
        if (val !== this.content) {
          this.setContent(val);
        }
      } else {
        this.setContent('');
      }
    },

    content(val) {
      this.$emit('input', val);
    }
  },
  mounted() {
    this.toolId = this.randomString(12)
    this.editorId = this.randomString(12)
    this.content = this.value
    this.$nextTick(() => {
      this.editor = new wangEditor(this.$refs[this.toolId], this.$refs[this.editorId])
      this.editor.customConfig.onchange = (html) => {
        // 監(jiān)控變化,同步更新到 textarea
        this.content = html
      }
      //配置圖片上傳服務(wù)器接口
      this.editor.customConfig.uploadImgServer = process.env.VUE_APP_BASE_API + '/file/upload/customizeDirUpload'
      // 文件名
      this.editor.customConfig.uploadFileName = 'file'
      // 配置上傳圖片請求頭部
      // this.editor.customConfig.uploadImgHeaders = {}
      // 上傳圖片鉤子函數(shù)
      this.editor.customConfig.uploadImgHooks = {
        before: function(xhr, editor, files) {
          // 圖片上傳之前觸發(fā)
          // xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,files 是選擇的圖片文件

          // 如果返回的結(jié)果是 {prevent: true, msg: 'xxxx'} 則表示用戶放棄上傳
          // return {
          //     prevent: true,
          //     msg: '放棄上傳'
          // }
        },
        success: function(xhr, editor, result) {
          // 圖片上傳并返回結(jié)果,圖片插入成功之后觸發(fā)
          // xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,result 是服務(wù)器端返回的結(jié)果
          // alert('成功')
        },
        fail: function(xhr, editor, result) {
          // 圖片上傳并返回結(jié)果,但圖片插入錯(cuò)誤時(shí)觸發(fā)
          // xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,result 是服務(wù)器端返回的結(jié)果
        },
        error: function(xhr, editor) {
          // 圖片上傳出錯(cuò)時(shí)觸發(fā)
          // xhr 是 XMLHttpRequst 對象,editor 是編輯器對象
        },
        timeout: function(xhr, editor) {
          // 圖片上傳超時(shí)時(shí)觸發(fā)
          // xhr 是 XMLHttpRequst 對象,editor 是編輯器對象
        },

        // 如果服務(wù)器端返回的不是 {errno:0, data: [...]} 這種格式,可使用該配置
        // (但是,服務(wù)器端返回的必須是一個(gè) JSON 格式字符串!??!否則會(huì)報(bào)錯(cuò))
        customInsert: function(insertImg, result, editor) {
          // 圖片上傳并返回結(jié)果,自定義插入圖片的事件(而不是編輯器自動(dòng)插入圖片?。。。?          // insertImg 是插入圖片的函數(shù),editor 是編輯器對象,result 是服務(wù)器端返回的結(jié)果

          // 舉例:假如上傳圖片成功后,服務(wù)器端返回的是 {url:'....'} 這種格式,即可這樣插入圖片:
          var url = result.data
          insertImg(url)

          // result 必須是一個(gè) JSON 格式字符串?。?!否則報(bào)錯(cuò)
        }
      }
      this.editor.create()
      this.editor.txt.html(this.value)
    })
  },
  methods: {
    // 生成隨機(jī)字符串id
    randomString(len) {
      len = len || 32
      let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /** **默認(rèn)去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      let maxPos = $chars.length
      let pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return 'a' + pwd
    },
    setContent(val) {
      this.editor.txt.html(val)
    }
  }
}
</script>

<style scoped>
  .toolbar {
    border: 1px solid #ccc;
  }
  .text {
    border: 1px solid #ccc;
    min-height: 200px;
  }
</style>

四、使用

import導(dǎo)入組件后,和使用輸入框一樣使用即可:

<rich-text v-model="html"></rich-text>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容