天天看點

wangEditor在vue架構下的使用

wangEditor是一個輕量級的微網誌富文本編輯器,在我最近的一個小項目中,與偶遇到部份内容在背景的編輯,需要使用富文本,但是第一次使用富文本編輯器的元件就踩了很多坑

首先這個項目的背景的基本架構是使用ruoyi自動生成的,ruoyi有自己封裝好的富文本編輯器元件,這個元件功能也比較完善,隻是他插入圖檔的功能是将圖檔轉化為base64直接插入到文本内,這就導緻文本會變得非常的大以至于無法直接插入到我們的資料庫裡,然後就使用了另外的元件,最終標明的就是wangEditor。

wangEditor在vue架構下的使用

他有較完善的官方文檔供我們閱讀,上手比較簡單,而且也會教你如何在vue架構中使用他的元件

首先在我們的項目中安裝元件

npm 安裝 

npm i wangeditor –save

wangEditor

是用

TypeScript

開發的元件,

我們使用的是vue架構,

是以我們還需要在項目各根目錄建立一個

tsconfig.json

輸入以下内容

{

    "compilerOptions": {

      "experimentalDecorators": true,

      "emitDecoratorMetadata": true,

      "lib": ["dom","es2016"],

      "target": "es5"

    },

    "include": ["./src/**/*"] 

}

           

然後就可以使用了

我們建立一個元件MEditor,上代碼

<template>
  <div>
    <div ref="editor" style="text-align:left">
    </div>
  </div>
</template>

<script>
  import E from 'wangeditor' //引入編輯器

  import {
    uploadPicture
  } from "@/api/resume/briefIntroduction";//圖檔上傳方法
  import {
    getToken
  } from "@/utils/auth";//擷取使用者驗證token
  export default {
    name: "MEditor",
    props:{
      /*編輯器的内容*/
      value: {
          type: String
      },
    },
    data: function() {
      return {
        editor:null,
        Title: '',
        Content: this.value,
      }
    },
    mounted: function() {
      let That = this;
      this.editor = new E(this.$refs.editor);
      this.editor.config.placeholder = ''
        //圖檔上傳數量限制
      this.editor.config.uploadImgMaxLength=1;
        //自定義圖檔上傳方法
      this.editor.config.customUploadImg=function(resultFiles, insertImgFn) {
        let data = new FormData;
        data.append('introductionPicture',resultFiles[0]);
          uploadPicture({
			  	Authorization: "Bearer" + getToken(),
			  },data).then(res=>{
            insertImgFn(res.imgUrl)
          });
          // 上傳圖檔,傳回結果,将圖檔插入到編輯器中
      };
      this.editor.config.onchange = function (newHtml) {
            That.$emit('change',newHtml)
      };//元件内容改變,将文本傳回到父元件
      this.editor.create();
      this.editor.txt.html(That.Content);//初始化編輯器内文本内容
    },
    watch:{
      value: {//監聽value的内容,如果發生改變将文本内容重新寫入編輯器
      	handler(val) {
      		if (val !== this.Content) {
      			this.Content = val === null ? "" : val;
      			if (this.editor) {
      				this.editor.txt.html(this.Content);
      			}
      		}
      	},
      	immediate: true,
      },
    },
      beforeDestroy() {
        // 銷毀編輯器
        this.editor.destroy()
        this.editor = null
      },
  }
</script>

           

父元件内使用

<MEditor :value="form.briefintroduction" @change="contentChange"></MEditor>
           

父元件監聽編輯器發出的内容改變事件,實作雙向綁定,其實可以修改為v-model,具體可以參考vue官方文檔。

contentChange(htmlContent){
      this.form.briefintroduction=htmlContent;
    }
           

繼續閱讀