Bootstrap

quill-editor使用方法,图片base64位转为url缩减字符长度,以及显示文字个数,光标位置等

  1. 下载
npm install vue-quill-editor

2.导入

import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

3.使用

 <!-- 富文本 -->
            <div class="editor-wrapper">
              <!-- 改进quill的图片base64功能,改为上传后拼接url,上传组件隐藏 -->
              <el-upload
                class="quill-upload"
                :action="photoUploadUrl"
                :show-file-list="false"
                :on-success="handleQuillImgSuccess"
                with-credentials
                accept="image/gif, image/jpeg, image/jpg, image/bmp, image/png"
                style="display: none">
                <i id="imgInput" class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
              <!--  -->
              <quill-editor ref="myQuillEditor" v-model="form.CONTENT" @change="onEditorChange($event)" :disabled="contentModel" :options="editorOption" />
              <span class="size-tip">
                {{TiLength}}/500
              </span>
            </div>

4.赋值与方法

const toolbarOptions = [
        ['bold', 'italic', 'underline', 'strike'], // toggled buttons
        ['blockquote', 'code-block'],

        [{ header: 1 }, { header: 2 }], // custom button values
        [{ list: 'ordered' }, { list: 'bullet' }],
        [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
        [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
        [{ direction: 'rtl' }], // text direction

        [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
        [{ header: [1, 2, 3, 4, 5, 6, false] }],

        [{ color: [] }, { background: [] }], // dropdown with defaults from theme
        [{ font: [] }],
        [{ align: [] }],
        ['clean'], // remove formatting button
        ['image','video'],
      ]
data(){
	return {
		photoUploadUrl: `${window.__GW_ENV__.BASE_API}sys/sysFile/upload`, //图片上传URL
      editorOption: {
        placeholder: '请输入内容',
        modules: {
            toolbar: {
              container: toolbarOptions,
              handlers: {
                // 重写点击组件上的图片按钮要执行的代码
                'image': function (value) {
                  that.$nextTick(() => {
                    document.querySelector('.quill-upload .el-icon-upload').click()
                  })
                }
              }
            }
          }
      },
      form: {
        CONTENT:'',
        // scType: 'complex', //模式 简单-simple 复杂-complex
      },
      
	}
},
methods: {
//富文本字数监听
    onEditorChange(event) {
      event.quill.deleteText(500,1);
      if(this.form.content===0){
        this.TiLength = 0
      }
      else{
        this.TiLength = event.quill.getLength()-1
      }
    },
    drawerOpen() {
      this.$refs.form && this.$refs.form.clearValidate()
      this.initEditor()
      if(this.currentData.id) {
        this.form= {
        TITLE:this.currentData.title,
        REMIND: this.currentData.remind, 
        REMIND_TIME: this.currentData.remindTime, 
        FREQUENCY: this.currentData.frequency,
        STOP: this.currentData.stop, 
        STOP_TIME: this.currentData.stopTime,
        ATTACHMENT:this.currentData.attachment?JSON.parse(this.currentData.attachment):[],
        CONTENT:this.currentData.content,
        STATUS:this.currentData.status
        // scType: 'complex', //模式 简单-simple 复杂-complex
        },
        this.form.ID = this.currentData.id
        //附件
        if (this.form.ATTACHMENT.length) {
          this.form.ATTACHMENT.forEach((item) => {
            this.fileList.push({
              name: item.name,
              url: `${window.__GW_ENV__.BPM_API}`+'sys/sysFile/download?fileId='+`${item.id}`,
            })
          })
        }
      }else {
       delete this.form.ID
      }
    },
    //抽屉回调——隐藏
    beforeClose(done) {
      this.clearFormValidate()
      this.form = {
        TITLE:"",
        REMIND: 'true', 
        REMIND_TIME: '', 
        FREQUENCY: '1',
        STOP: '0', 
        STOP_TIME: '',
        ATTACHMENT:[],
        CONTENT:'',
        STATUS:'0',
      },
      this.fileList = []
      if(typeof done =='function'){
        done()
      }else {
        this.drawerVisible = false
      }
    },
    // 初始化富文本编辑器,编辑回显以及光标定位
    initEditor() {
      this.$nextTick(() => {
        //编辑时光标定位以及回显富文本的文字字数
        if(this.currentData.id) {
          this.TiLength = this.editor.getLength()-1
          let range = this.editor.getSelection()
          if(range) {
            this.editor.setSelection(range.index + this.TiLength)
          }
        }
        // console.log(range,'rage')
        this.editor.getModule('toolbar').addHandler('image', this.imgHandler)
        // 自定义粘贴图片功能
        this.editor.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
              const formData = new FormData()
              formData.append('file', file)
              uploadFile(formData).then((res) => {
                let range = this.editor.getSelection()
                // let range = this.editor.selection.savedRange.index
                if (range) {
                  // 在当前光标位置插入图片
                  this.editor.insertEmbed(range.index, 'image', `${window.__GW_ENV__.BASE_API}/sys/sysFile/download?fileId=${res.data}`)
                  // 将光标移动到图片后面
                  this.editor.setSelection(range.index + 1)
                }
              })
            })
          }
        }, false)
      })
    },
    // 点击quill-editor图片ICON触发事件
    imgHandler(state) {
      this.addRange = this.editor.getSelection()
      if (state) {
        // 选择并上传一张图片
        const fileInput = document.getElementById('imgInput')
        fileInput.click() // 加一个触发事件
      }
    },
    // quill-editor的图片上传成功事件
    handleQuillImgSuccess(response, file, fileList) {
      // 图片的远程路径
      const value = `${window.__GW_ENV__.BASE_API}sys/sysFile/download?fileId=${file.response.data}`
      //https://oa-alpha.ecloud.work/oa-single/sys/sysFile/download?fileId=425406546158288897
      // 将图片添加到富文本内容区域
      this.addRange = this.editor.getSelection()
      // 调用编辑器的 insertEmbed 方法,插入URL
      this.editor.insertEmbed(
        this.addRange !== null ? this.addRange.index : 0,
        'image',
        value
      )
    },
    //清除表单验证
    clearFormValidate() {
      this.$refs.form && this.$refs.form.clearValidate()
    },
    //附件上传
    handleImport({file}) {
      const formData = new FormData();
      formData.append('file', file);
      uploadFile(formData)
        .then((res) => {
          if (res.code == 200 && res.isOk) {
            console.log(this.form.ATTACHMENT)
            this.form.ATTACHMENT.push({
              id: res.data,
              name: file.name,
              uID: file.uid,
              uName:this.$store.getters.name,
              size: file.size,
              date:new Date().format('yyyy-MM-dd HH:mm:ss')
            })
            this.$message({
              message: '上传成功',
              type: 'success',
            });
          }
        })
        .catch((error) => {
          this.$message({
            message: '上传失败',
            type: 'error',
          });
          console.error(error);
        });
    },
    //删除附件
    handleFileRemove(file, fileList) {
      if (file && file.status==="success") {
        return this.$confirm(`确定移除 ${file.name}`)
      } 
    },
    //查看上传附件
    handleFilePreview(file) {
      fileDownload(file.id, file.name)
    }
  }
;