Quill富文本的使用以及自定义图片和视频处理事件

Stella981
• 阅读 847

Quill富文本的使用    官网 https://quilljs.com/docs/quickstart/

1、安装quill

使用  mpn i quill -S 

2、新建myquil.vue文件,内容如下

<template>
  <div class="quill-editor">
    <slot name="toolbar"></slot>
    <div ref="editor"></div>
    <div id="editor"></div>
    <!-- 测试video标签 -->
    <!-- <video src="https://www.w3school.com.cn/i/movie.mp4" controls="controls" width="100%" height="100%" webkit-playsinline="true" playsinline="true" x5-playsinline="true"></video> -->
    <input id="uploadImg" ref="uploadImg" type="file" style="display:none" accept="image/jpeg, image/png"
      @change="uploadImage">
    <input id="uploadVideo" ref="uploadVideo" type="file" style="display:none" accept="video/*" @change="uploadVideo">
  </div>
</template>

<script>
// require sources
import _Quill from 'quill'
import defaultOptions from './options'
const Quill = window.Quill || _Quill

// pollfill
if (typeof Object.assign != 'function') {
  Object.defineProperty(Object, 'assign', {
    value(target, varArgs) {
      if (target == null) {
        throw new TypeError('Cannot convert undefined or null to object')
      }
      const to = Object(target)
      for (let index = 1; index < arguments.length; index++) {
        const nextSource = arguments[index]
        if (nextSource != null) {
          for (const nextKey in nextSource) {
            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey]
            }
          }
        }
      }
      return to
    },
    writable: true,
    configurable: true
  })
}
//视频处理
const BlockEmbed = Quill.import('blots/block/embed')
class VideoBlot extends BlockEmbed {
  static create(value) {
    let node = super.create()
    node.setAttribute('src', value.url)
    node.setAttribute('controls', value.controls)
    node.setAttribute('width', value.width)
    node.setAttribute('height', value.height)
    node.setAttribute('webkit-playsinline', true)
    node.setAttribute('playsinline', true)
    node.setAttribute('x5-playsinline', true)
    return node
  }

  static value(node) {
    return {
      url: node.getAttribute('src'),
      controls: node.getAttribute('controls'),
      width: node.getAttribute('width'),
      height: node.getAttribute('height')
    }
  }
}

VideoBlot.blotName = 'simpleVideo'
VideoBlot.tagName = 'video'
Quill.register(VideoBlot)

// export
export default {
  name: 'myquill',
  data() {
    return {
      _options: {},
      _content: '',
      defaultOptions
    }
  },
  props: {
    content: String,
    value: String,
    disabled: {
      type: Boolean,
      default: false
    },
    options: {
      type: Object,
      required: false,
      default: () => ({})
    },
    globalOptions: {
      type: Object,
      required: false,
      default: () => ({})
    }, //文件大小阈值,单位字节B,大于1M=1024B
    threshold: {
      type: Number,
      default: 1025
    },
    //宽度
    width: {
      type: Number,
      default: 1080
    },
    //高度
    height: {
      type: Number,
      default: 100
    },
    //高度
    quality: {
      type: Number,
      default: 0.2
    }
  },
  mounted() {
    this.initialize()
  },
  beforeDestroy() {
    this.quill = null
    delete this.quill
  },
  methods: {
    // Init Quill instance
    initialize() {
      if (this.$el) {
        // Options
        this._options = Object.assign({}, this.defaultOptions, this.globalOptions, this.options)

        // Instance
        this.quill = new Quill(this.$refs.editor, this._options)

        this.quill.getModule('toolbar').addHandler('image', this.uploadImageHandler)

        this.quill.getModule('toolbar').addHandler('video', this.uploadVideoHandler)

        this.quill.enable(false)

        // Set editor content
        if (this.value || this.content) {
          this.quill.pasteHTML(this.value || this.content)
        }

        // Disabled editor
        if (!this.disabled) {
          this.quill.enable(true)
        }

        // Mark model as touched if editor lost focus
        this.quill.on('selection-change', (range) => {
          if (!range) {
            this.$emit('blur', this.quill)
          } else {
            this.$emit('focus', this.quill)
          }
        })

        // Update model if text changes
        this.quill.on('text-change', (delta, oldDelta, source) => {
          let html = this.$refs.editor.children[0].innerHTML
          const quill = this.quill
          const text = this.quill.getText()
          if (html === '<p><br></p>') html = ''
          this._content = html
          this.$emit('input', this._content)
          this.$emit('change', { html, text, quill })
        })

        // Emit ready event
        this.$emit('ready', this.quill)
      }
    },
    uploadImageHandler() {
      const input = document.querySelector('#uploadImg')
      input.value = ''
      input.click()
      // this.$refs.uploadImage.value = "";
      // this.$refs.uploadImage.click();
    },

    //el-upload文件上传的处理逻辑
    beforeUpload(file) {
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLessthan2M = file.size / 1024 / 1024 < 2 //最大限制2M

      if (!isJPGorPNG) {
        this.$message.error('上传图片只能是 JPG,PNG 格式!')
      }
      if (!isLessthan2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPGorPNG && isLessthan2M
    },
    uploadImage(event) {
      var file = event.target.files[0]
      const that = this
      if (that.beforeUpload(file)) {
        //上传图片大于1M进行压缩
        if (file.size / 1024 > that.threshold) {
          this.condenseFile(file, function(base64Codes) {
            that.uploadImageSucess(1, base64Codes)
          })
        } else {
          this.convertBase64Url(file)
        }
        this.uploadImageSucess(1, this.condenseBase64)
      }
    },

    uploadVideoHandler() {
      const input = document.querySelector('#uploadVideo')
      input.value = ''
      input.click()
      // this.$refs.uploadVideo.value = "";
      // this.$refs.uploadVideo.click();
    },

    uploadVideo(event) {
      if (typeof XMLHttpRequest === 'undefined') {
        return
      }
      var xhr = new XMLHttpRequest()
      const formData = new FormData()
      //   formData.append('upload_file', event.target.files[0])
      var text = '成功'
      const that = this
      xhr.onload = function onload() {
        if (xhr.status < 200 || xhr.status >= 300) {
          // return option.onError(this.getError(action, option, xhr));
          text = xhr.responseText || xhr.response
          alert('失败' + text)
        }
        // console.log(text)
        that.uploadImageSucess(2, 'https://www.w3school.com.cn/i/movie.mp4')
      }

      xhr.open('post', 'http://localhost:8088/test', true)
      xhr.send(formData)
    },

    uploadImageSucess(type, url) {
      //   const addImageRange = this.quill.getSelection()
      //   const newRange = 0 + (addImageRange !== null ? addImageRange.index : 0)
      let newRange = this.quill.selection.savedRange.index

      if (type === 1) {
        // const url =
        //   'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        this.quill.insertEmbed(newRange, 'image', url)
        this.quill.setSelection(1 + newRange)
        console.log(
          '$ uploadImageSucess 7777 his.quill.selection.savedRange.index:{this.quill.selection.savedRange.index}'
        )
      } else {
        // const url = 'https://www.w3school.com.cn/i/movie.mp4'
        this.quill.insertEmbed(newRange, 'simpleVideo', {
          url,
          controls: 'controls',
          width: '320',
          height: '240',
          autoplay: 'autoplay'
        })
        this.quill.setSelection(1 + newRange)
      }
      //获取内容
      //   console.log(this.quill.getContents())
      //   console.log(this.quill.getText())
      //   var html = this.quill.root.innerHTML
      // alert(html);
      //   console.log(html)
      //   var xx = this.quillGetHTML(this.quill.getContents())
      //  alert(xx);
      //   console.log(xx)
    },

    //获取富文本信息
    quillGetHTML(inputDelta) {
      //护球编辑器的内容
      var tempCont = document.createElement('div')
      new Quill(tempCont).setContents(inputDelta)
      return tempCont.getElementsByClassName('ql-editor')[0].innerHTML
    },

    //文件转换成base64字符串
    convertBase64Url(file) {
      var ready = new FileReader()
      ready.readAsDataURL(file)
      const that = this
      ready.onload = function() {
        var fileResult = this.result
        that.uploadImageSucess(1, fileResult)
      }
    },

    //压缩文件第一步
    condenseFile(file, callback) {
      var ready = new FileReader()
      ready.readAsDataURL(file)
      const that = this
      ready.onload = function() {
        var fileResult = this.result
        that.condenseCanvasDataURL(fileResult, callback)
      }
    },

    //压缩文件第二步,重新绘制图片,并返回压缩以后的文件的base64的值,可以把base64的值作为参数传给回调接口
    condenseCanvasDataURL(path, callback) {
      var img = new Image()
      img.src = path
      const that1 = this
      img.onload = function() {
        var that = this
        //默认压缩后图片规格
        var quality = 0.5
        var w = that.width
        var h = that.height
        var scale = w / h
        //计算图片的实际大小,设置宽高比例
        w = w > that1.width ? that1.width : w
        h = w / scale
        if (that1.quality && that1.quality > 0 && that1.quality <= 1) {
          quality = that1.quality
        }

        //生成canvas
        var canvas = document.createElement('canvas')
        var ctx = canvas.getContext('2d')
        // 创建属性节点
        var anw = document.createAttribute('width')
        anw.nodeValue = w
        var anh = document.createAttribute('height')
        anh.nodeValue = h
        canvas.setAttributeNode(anw)
        canvas.setAttributeNode(anh)
        ctx.drawImage(that, 0, 0, w, h)

        var base64 = canvas.toDataURL('image/jpeg', quality)
        // 回调函数返回压缩以后的文件的base64的值
        callback(base64)
      }
    },

    condenseconvertBase64UrlToBlob(urlData) {
      var arr = urlData.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },

    //压缩文件第一步
    uploadFile(event) {
      if (typeof XMLHttpRequest === 'undefined') {
        return
      }
      var xhr = new XMLHttpRequest()
      if (xhr.upload) {
        xhr.upload.onprogress = function progress(e) {
          if (e.total > 0) {
            e.percent = (e.loaded / e.total) * 100
          }
          //   option.onProgress(e);吧上传进度回调给其他的接口
        }
      }
      const formData = new FormData()
      //   formData.append('upload_file', event.target.files[0]);
      var file = event.target.files[0]
      const that = this
      //上传图片大于1M进行压缩
      if (file.size / 1024 > 1025) {
        that.photoCompress(file, { quality: 0.2 }, function(base64Codes) {
          var bl = that.convertBase64UrlToBlob(base64Codes)
          formData.append('files', bl, file.name)
        })
      } else {
        formData.append('files', file, file.name)
      }
      xhr.onerror = function error(e) {
        alert('失败' + e)
      }
      var text = '成功'
      xhr.onload = function onload() {
        if (xhr.status < 200 || xhr.status >= 300) {
          text = xhr.responseText || xhr.response
          alert('失败' + text)
        }
        // console.log(text)
        //上传成功,根据xhr.response的返回信息中的url,将url插入到编辑区
        that.uploadImageSucess(1)
      }

      xhr.open('post', 'http://localhost:8084/test', true)
      xhr.send(formData)
    },
    //图片压缩处理 压缩文件第一步
    photoCompress(file, objCompressed, objDiv) {
      var ready = new FileReader()
      ready.readAsDataURL(file)
      const that = this
      ready.onload = function() {
        var fileResult = this.result
        that.canvasDataURL(fileResult, objCompressed, objDiv)
      }
    },
    //压缩文件第二步
    canvasDataURL(path, objCompressed, callback) {
      var img = new Image()
      img.src = path
      img.onload = function() {
        var that = this
        //默认压缩后图片规格
        var quality = 0.5
        var w = that.width
        var h = that.height
        var scale = w / h
        //实际要求
        w = objCompressed.width || w
        h = objCompressed.height || w / scale
        if (objCompressed.quality && objCompressed.quality > 0 && objCompressed.quality <= 1) {
          quality = objCompressed.quality
        }

        //生成canvas
        var canvas = document.createElement('canvas')
        var ctx = canvas.getContext('2d')
        // 创建属性节点
        var anw = document.createAttribute('width')
        anw.nodeValue = w
        var anh = document.createAttribute('height')
        anh.nodeValue = h
        canvas.setAttributeNode(anw)
        canvas.setAttributeNode(anh)
        ctx.drawImage(that, 0, 0, w, h)

        var base64 = canvas.toDataURL('image/jpeg', quality)
        // 回调函数返回base64的值
        callback(base64)
      }
    },
    //上传文件压缩的处理完成之后,回调方法 压缩文件第三步
    convertBase64UrlToBlob(urlData) {
      var arr = urlData.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    }
  },
  watch: {
    // Watch content change
    content(newVal, oldVal) {
      if (this.quill) {
        if (newVal && newVal !== this._content) {
          this._content = newVal
          this.quill.pasteHTML(newVal)
        } else if (!newVal) {
          this.quill.setText('')
        }
      }
    },
    // Watch content change
    value(newVal, oldVal) {
      if (this.quill) {
        if (newVal && newVal !== this._content) {
          this._content = newVal
          this.quill.pasteHTML(newVal)
        } else if (!newVal) {
          this.quill.setText('')
        }
      }
    },
    // Watch disabled change
    disabled(newVal, oldVal) {
      if (this.quill) {
        this.quill.enable(!newVal)
      }
    }
  }
}
</script>

options.js文件内容如下

export default {
  theme: 'snow',
  boundary: document.body,
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ header: 1 }, { header: 2 }],
      [{ list: 'ordered' }, { list: 'bullet' }],
      [{ script: 'sub' }, { script: 'super' }],
      [{ indent: '-1' }, { indent: '+1' }],
      [{ direction: 'rtl' }],
      [{ size: ['small', false, 'large', 'huge'] }],
      [{ header: [1, 2, 3, 4, 5, 6, false] }],
      [{ color: [] }, { background: [] }],
      [{ font: [] }],
      [{ align: [] }],
      ['link', 'image', 'video', 'formula'],
      ['clean']
    ]
  },
  // placeholder: 'Insert text here ...',
  placeholder: '我的编辑器占位符...',
  readOnly: false
}

3、再其他的vue文件中引用,内容如下

<template>
  <!-- 使用 quill富文本编辑器组件-->
  <myquill v-model="content" ref="myQuillEditor"></myquill>
</template>

<script>
import myquill from "./myquil.vue"; //导入定义的myquil.vue文件
export default {
  name: "App",
  components: {
    myquill //注册quill富文本编辑器组件
  },
  data() {
    return {
      content: "quill富文本编辑器初始值"
    };
  }
};
</script>

<style scoped>
.ql-container.ql-snow {
  margin-bottom: 22px;
}
.ql-editor {
  height: 500px;
}
</style>
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这