天天看點

vue-quill-editor自定義上傳圖檔

vue-quill-editor 在粘貼圖檔和選擇圖檔上傳的時候會自動轉成base64格式,但是base64資料量太大不利于存儲,我們可以将圖檔上傳到伺服器,然後存儲一條連結更好

首先配置一下圖檔上傳的事件:

editorOption: {
        placeholder: '請輸入内容',
        modules:{
          "emoji-toolbar": true,
          "emoji-shortname": true,
          toolbar: {
            container: [],// toolbar工具欄的工具選項(預設展示全部) toolOptions:
          },
          clipboard:{
            matchers:[
              ['img',this.handleCustomMatcher]
            ]
          },
        }
      },
           

這個是配置的粘貼圖檔的事件

vue-quill-editor自定義上傳圖檔
//将粘貼的圖檔替換為空
    handleCustomMatcher(node,Delta){
      console.log(node);
      console.log(Delta);
      let ops = [];
      Delta.ops.forEach(op=>{
        if(op.insert && typeof op.alt === 'string'){
          ops.push({
            insert:op.insert,
          })
        }
      })
      Delta.ops = ops
      return Delta
    },
           

在vue渲染完成之後,擷取vue-quill,重置粘貼實踐:

mounted() {
    //  自定義粘貼圖檔功能
    let quill = this.$refs.myQuillEditor.quill
    let length = quill.selection.savedRange.index
    quill.root.addEventListener('paste', evt => {
      if (evt.clipboardData && evt.clipboardData.files && evt.clipboardData.files.length) {
        evt.preventDefault();
        [].forEach.call(evt.clipboardData.files, file => {
          if (!file.type.match(/^image\/(gif|jpe?g|a?png|bmp)/i)) {
            return
          }
          console.log(file);
          var formdata=new FormData();
          formdata.append("label_images",file);
          const loading = this.$loading({
            lock: true,
            text: '圖檔加載中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          //我這裡用了jq的ajax,可以用axios,
          this.JQ.ajax({
              url:'上傳圖檔的接口',
              type:'post',
              data:formdata,
              dataType:'json',
              processData: false,   // jQuery不要去處理發送的資料
              contentType: false,   // jQuery不要去設定Content-Type請求頭
              success:function(ret){
                  //.把圖檔插到光标的地方(第三個參數是圖檔的url)
                  quill.insertEmbed(length, 'image', 這裡寫接口回傳的url)
                  //把光标移到圖檔的後面
                  quill.setSelection(length + 1);
                  loading.close();
              },
              error:function(error){
                alert(error)
              }
          })
        })
      }
    }, false);
    
  },
           

這樣自定義粘貼圖檔就完成了