【Vue】Quill-Editor富文本编辑器

  • 基于Vue的Quill-Editor富文本编辑器

#1#-> 在vue项目中安装插件

npm install vue-quill-editor --save

 #2#-> 在项目中引用插件,全局或者单组件引入,具体可参考

https://www.jianshu.com/p/a6cba69d6e49 

https://www.cnblogs.com/zly430/p/10895307.html

这里采用的全局引用方式,在main.js中引入插件

import VueQuillEditor from 'vue-quill-editor'
// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

 #3#-> 禁用富文本编辑器默认的图片上传

Quill-Editor可以在编辑框中直接插入图片,编辑器会把图片转成base64格式和文本一起存入数据库,但如果上传图片大小过大,会造成传输数据过大,数据库数据负载严重,降低效率。

一般做法是把图片和附件单独上传到服务器端的文件夹里,数据库存放文件对应的名称。

<div id="div_my_quill_editor">
    <quill-editor class="ql-editor" id="myQuillEditor" 
                  v-model="content" ref="myQuillEditor"
                  :options="editorOption"
                  @change="onEditorChange"/>
</div>
<script>
  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'], // toggled buttons
    [{ header: 1 }, { header: 2 }], // custom button values
    [{ list: 'ordered' }, { list: 'bullet' }],
    [{ 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: [] }],
    ['link'], // 去掉上传图片
    // ['link', 'image'],
    ['clean']
  ]
 export default {
     data () {
         return {
                 // 富文本编辑器
                 content: '',
                 editorOption: {
                      placeholder: '编辑文章内容',
                      theme: 'snow', // or 'bubble'
                      modules: {
                        toolbar: {
                        container: toolbarOptions,
                         handlers: {
                           image: function (value) {
                                // if (value) {
                                // 触发input框选择图片文件
                                //   document.querySelector('.avatar-uploader input').click()
                                // } else {
                                   //   this.quill.format('image', false)
                                // }
                                this.quill.format('image', false) // 禁用quill内部上传图片
                            }
                         }
                       }
                     }
                },   
         }
     }
 }
</script>

  #4#-> 结合Element-UI 自定义图片和文件上传

定义图片和文件上传组件

 <!--图片上传-->
        <el-form-item label="上传图片">
          <el-upload
            action
            accept=".png,.jpg"
            :multiple="true"
            list-type="picture-card"
            :auto-upload="false"
            :file-list="imgList"
            :on-change="handleChange"
            :http-request="httpRequest"
            ref="uploadImg"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url" alt=""
              >
              <span class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-preview"
          @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete"
          @click="handleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <!-- 上传文件 -->
        <el-form-item label="上传文件">
          <label>仅支持<span
            style="font-weight: bold">.xls/.xlsx/.doc/.docx/.pdf/.zip/.rar</span>格式的文件,且单个文件大小不超过<span
            style="font-weight: bold;color: red">10MB</span>
          </label>
          <el-upload
            action
            ref="uploadFile"
            accept=".xls,.xlsx,.doc,.docx,.pdf,.zip,.rar"
            :limit="5"
            :multiple="true"
            :file-list="fileList"
            :auto-upload="false"
            :on-exceed="handleExceed2"
            :on-change="handleChange2"
            :on-remove="handleRemove2"
            :before-upload="beforeUpload2"
            :http-request="httpRequest2"
            :on-success="handleSuccess2"
            :on-error="handleError2">
            <el-button slot="trigger" size="medium" type="primary">选取文件</el-button>
          </el-upload>
        </el-form-item>

data定义

// 图片上传
imgList: [],
dialogImageUrl: '',
dialogVisible: false,
disabled: false,

// 文件上传
fileList: []

 #->【图片上传】

     handleRemove (file, imgList) {
        if (file) {
          const arr = [] // 新建一个list
          if (this.imgList.length === 1) { // 当前只有一个
            this.imgList = [] // 直接清空
          } else {
            this.imgList.forEach(function (item, index) {
              if (item.uid !== file.uid) {
                arr.push(item)
              }
            })
            this.imgList = arr
          }
        }
      },
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      // 文件状态改变
      handleChange (file, imgList) {
        console.log(file)
        console.log(imgList)
        this.imgList = imgList
      },
      // 覆盖默认的上传行为,可以自定义上传的实现
      httpRequest (param) {
        this.myFormData.append('img', param.file) // 多个图片一次提交
      },

  #->【文件上传】

      // 超过文件上传最大个数
      handleExceed2 (files, fileList) {
        this.$message.warning('很抱歉当前支持最大上传文件个数为 5 个!')
      },
      // 文件上传到服务器之前的文件校验
      beforeUpload2 (file) {
        console.log(file)
        const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
        const size = file.size / 1024 / 1024
        if (extension !== 'xls' && extension !== 'xlsx' && extension !== 'doc' && extension !== 'docx' && extension !== 'pdf' && extension !== 'zip' && extension !== 'rar') { // 校验文件格式
          this.$message.warning('只支持上传后缀名为.xls/.xlsx/.doc/.docx/.pdf/.zip/.rar格式的文件')
        }
        if (size > 10) { // 校验文件大小
          this.$message.warning('单个文件大小不能超过10MB')
        }
      },
      // 文件删除
      handleRemove2 (file) {
        if (file && file.status === 'success') {
          this.fileList.splice(this.fileList.findIndex(item => item.url === file.url), 1)
        }
      },
      // 文件状态改变
      handleChange2 (file, fileList) {
        // console.log('handleChange2')
        // console.log(file)
        // console.log(fileList)
        this.fileList = fileList
      },
      // 文件上传成功
      handleSuccess2 (response, file, fileList) {
        console.log(response)
        this.$message.success(fileList.length + '个文件上传成功!')
      },
      // 文件上传失败
      handleError2 (err, file, fileList) {
        console.log('-------handleError-------')
        console.log(err)
        this.$message.error('文件上传失败')
      },
      // 覆盖默认的上传行为,可以自定义上传的实现
      httpRequest2 (param) {
        this.myFormData.append('file', param.file) // 多个文件一次提交
      },

#->【表单提交】

      // 表单提交
      submitForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 组织要提交的数据
            this.myFormData = new FormData() // FormData对象
            this.$refs.uploadImg.submit() // 上传图片
            this.$refs.uploadFile.submit() // 上传文件
            // 封装传递数据
            this.submitArticleInfo = this.packageSubmitData()
            this.myFormData.append('articleInfo', JSON.stringify(this.submitArticleInfo)) // 追加文章信息
            // 请求后台上传数据的接口
            this.$http.post('/Upload/', this.myFormData, {
              headers: { 'Content-Type': 'multipart/form-data' }
              // url: '/upload/import/',
              // data: formData
              // method: 'post'
            }).then(res => {
              console.log('-------res--------')
              console.log(res.data)
            }, err => {
              console.log('-------err--------')
              console.log(err)
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },

[参考]

1.vue-quill-editor上传内容由于图片是base64的导致字符太长的问题解决
https://blog.csdn.net/qq_34595425/article/details/106425105

2.VueQuillEditor富文本上传图片-非base64
https://www.imooc.com/article/305320

3.Vue+Element UI+vue-quill-editor富文本编辑器及插入图片自定义
https://www.jb51.net/article/167984.htm

4.富文本编辑vue-quill-editor自定义图片、文件上传
https://www.jianshu.com/p/9e4e4d955d0f

5.富文本编辑vue-quill-editor上传图片
https://blog.csdn.net/weixin_43840809/article/details/107786126

6.「前端早读君002」改造vue-quill-editor: 结合element-ui上传图片到服务器
https://segmentfault.com/a/1190000012620431

7.vue quill-editor图片上传,vue文件上传功能
https://www.pianshen.com/article/188082956/

8.vue 调用图片(服务器和本地)
https://www.cnblogs.com/linzhifen5/p/11771662.html

9.vue-quill-editor 自定义图片上传调整图片大小保存时删除服务器多余图片
https://www.cnblogs.com/guoyanhui-2016/p/11474652.html

10.富文本编辑器 删除图片问题
https://bbs.csdn.net/topics/390809074

11.vue实战024:Vue-Quill-Editor自定义图片上传
https://blog.csdn.net/kevinfan2011/article/details/90712463

12.Element-ui实现合并多图上传(一次请求多张图片)
https://segmentfault.com/a/1190000015834181

13.【问题记录】ElementUI上传组件使用before-upload钩子校验失败时的问题处理

https://www.cnblogs.com/jiafifteen/p/11550769.html

 

  • Quill-Editor富文本编辑器空格回显失败问题记录

先按照这个文章https://www.pianshen.com/article/35211597744/修改了

match = match.replace(/[^\u00a0]/g, ' '); 
match = match.replace(/[^\u00a0]/g, '&nbsp;'); 

都没有成功,还是按空格处理的,取出来显示到页面上空格被直接过滤掉了

 

翻到这篇文章https://ask.csdn.net/questions/770701

我也遇到了同样的问题,参考网上很多方式都是直接在插件使用的时候添加一个 class = 'quill-editor',能解决空格回显的问题,这个插件估计之前是能够自行替换的,现在不知道为什么不能替换了。

解决办法:自己替换咯,在提交文本数据到数据库的时候,先把这段HTML中的空格处理成 '&nbsp;'

  submitData.content = this.content.replace(/[\s]/gi, '&nbsp;') // 替换空格

文本渲染的时候记得使用v-html填充即可

<div v-html=articleInfo.content></div>

需要注意的是,下面3种写法,前2种都自行省略了前面的空格,同时无论&nbsp;有多少个只算了1个空格,只有第3种方式是成功的

<p>测试1:    首行缩进测试  空格</p>
<p>测试2:&nbsp;&nbsp;&nbsp;&nbsp;首行缩进测试&nbsp;&nbsp;空格</p>
<p v-html="'测试3:&nbsp;&nbsp;&nbsp;&nbsp;首行缩进测试&nbsp;&nbsp;空格'"></p>

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值