vue中使用vue-quill-editor并且粘贴直接上传图片

1.安装
npm install vue-quill-editor 
2.引入到项目中
        有两种挂载方式: 全局挂载 和 在组件中挂载,根据自己的项目需求选择,一般用到富文本编辑都是在某一个项目中,这里只写在项目中挂载的方式

import { quillEditor } from 'vue-quill-editor'
 
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
 
export default {
  components: {
    quillEditor
  }
}
3.在页面上写组件

<el-upload v-show="false" id="quill-upload" ref="annexUpload" action="上传的路径" name="content" :limit="1" list-type="picture" :on-exceed="handleExceed" :on-error="handleError" :file-list="uploadList" :with-credentials="true" :auto-upload="true" />
<quill-editor
    v-model="content"
    ref="myQuillEditor"
    :options="editorOption"
    @change="onEditorChange($event)"
</quill-editor>

// 内容改变事件
  onEditorChange({ quill, html, text }) {
    console.log('editor change!', quill, html, text)
    this.content = html

      this.$emit('change', html)

  },

  // 文件上传限制

    handleExceed(files, fileList) {

      this.$message.warning(`当前限制一次性上传最多 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`)

    },

    // 文件上传失败提示

    handleError(err, file, fileList) {

      this.$message.warning(`文件上传失败,请尝试重新上传,文件失败原因为: ${err}`)

    }


4.配置option

  editorOption: {

        placeholder: '请在这里输入文字或粘贴图片',

        theme: 'snow',

        modules: {

          toolbar: {

            container: toolbarOptions,

            handlers: {

              image: function(value) {

                if (value) {

                  document.querySelector('#quill-upload input').click()

                } else {

                  this.quill.format('image', false)// 禁用quill内部上传图片

                }

              }

            }

          }

        }

      }

toolbarOptions:[

  [],

  // ['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'],

  ['clean']

]

 5.初始化编辑器并添加粘贴事件

 粘贴图片调用接口,转换base64格式图片

// 初始化

    initPic() {

      if (this.init) {

        setTimeout(() => {

          this.init = false

          toolbarOptions[0] = ['image']

          const quill = this.$refs.myQuillEditor.quill

          this.$forceUpdate()

          quill.root.addEventListener(

            'paste',

            (evt) => {

              if (evt.clipboardData && evt.clipboardData.files && evt.clipboardData.files.length) {

                evt.preventDefault(); // 必须阻止默认行为,会粘贴两次,并且图片的base64格式

                [].forEach.call(evt.clipboardData.files, (file) => {

                  if (!file.type.match(/^image\/(gif|jpe?g|a?png|bmp)/i)) {

                    return

                  }

                  var formData = new FormData()

                  formData.append('uploadFile', file)

                  uploadPicTask({

                    data: formData

                  }).then((res) => {

                    var range = quill.getSelection()

                    if (range) {

                      // this.ruleForm.problemPics = this.ruleForm.problemPics + ',' + res.data

                      const quill = this.$refs.myQuillEditor.quill

                      const length = quill.getSelection().index

                      quill.insertEmbed(length, 'image', '/api/management/problem/pic/' + res.data)

                      quill.setSelection(length + 1)

                      // eslint-disable-next-line no-unused-vars

                      let fileType = null

                      if (file.raw && file.raw.type) {

                        fileType = file.raw.type

                      } else {

                        fileType = file.type

                      }

                      this.uploadList = []

                      this.$refs.myQuillEditor.quill.setSelection(range.index + 1)

                    }

                  })

                })

              }

            },

            false

          )

        }, 10)

      }

    },

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用`vue-quill-editor`进行图文粘贴时,复制的图片实际上以base64的形式进行上传。然而,将base64写进数据库并不是一个好的做法。因此,解决思路是将复制的图片上传至服务器,然后将服务器返回的图片地址作为img标签插入到富文本编辑器,这样就可以正确显示图片了。以下是一个解决思路的代码实例供参考: ```javascript mounted() { let quill = this.$refs.myQuillEditor.quill; 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; } const formData = new FormData(); formData.append("pictureFile", file); makdwnImg(formData) .then((res) => { if (res.data.code == 200) { let quill = this.$refs.myQuillEditor.quill; let length = quill.getSelection().index; quill.insertEmbed(length, "image", res.data.data); quill.setSelection(length + 1); } }) .catch((err) => { console.error(err); }); }); } }, false); }, ``` 通过这段代码,你可以在`vue-quill-editor`实现图文粘贴图片并正确显示图片。需要注意的是,你需要根据你自己的项目做一些适应性的调整。希望这能帮到你!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [vue-quill-editor粘贴图片,vue-quill-editor复制图片](https://blog.csdn.net/weixin_43131046/article/details/116490735)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值