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

本文介绍如何在Vue项目中集成vue-quill-editor富文本编辑器,并实现自定义功能如图片上传、粘贴事件处理等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

      }

    },

### Vue3 中集成和使用 vue-quill-editor 的方法及教程 在 Vue3 项目中集成 `vue-quill-editor` 富文本编辑器需要特别注意版本兼容性问题。以下是详细的集成与使用教程: #### 1. 安装依赖 Vue3 使用的是 `@vueup/vue-quill`,这是专门为 Vue3 开发的 Quill 编辑器插件。安装命令如下: ```bash npm install @vueup/vue-quill ``` 此外,如果需要实现图片拖拽、粘贴以及缩放功能,还需要安装以下两个模块: ```bash npm install quill-image-drop-module npm install quill-image-resize-module ``` #### 2. 引入样式 Quill 编辑器的样式文件必须被引入到项目中,否则界面会显示异常。可以在项目的入口文件(如 `main.js` 或 `main.ts`)中添加以下代码: ```javascript import '@vueup/vue-quill/dist/vue-quill.snow.css'; // 雪花主题样式 // 如果需要其他主题,可以引入不同的样式文件 ``` #### 3. 全局挂载 在 Vue3 中,可以通过插件的形式全局挂载 `@vueup/vue-quill`。示例如下: ```javascript import { createApp } from 'vue'; import App from './App.vue'; import { QuillEditor } from '@vueup/vue-quill'; const app = createApp(App); app.component('QuillEditor', QuillEditor); // 注册组件 app.mount('#app'); ``` #### 4. 组件内使用Vue3 的组件中可以直接使用 `<QuillEditor>` 标签来创建富文本编辑器。以下是一个简单的示例: ```vue <template> <div> <QuillEditor v-model:content="editorContent" contentType="html" /> </div> </template> <script> import { ref } from 'vue'; import { QuillEditor } from '@vueup/vue-quill'; export default { components: { QuillEditor }, setup() { const editorContent = ref('<p>Hello World</p>'); // 初始内容 return { editorContent }; }, }; </script> ``` #### 5. 配置扩展功能 为了实现图片拖拽、粘贴以及缩放功能,需要对 Quill 编辑器进行扩展配置。以下是具体步骤: ##### 5.1 引入扩展模块 在项目中引入 `quill-image-drop-module` 和 `quill-image-resize-module`: ```javascript import ImageDrop from 'quill-image-drop-module'; import ImageResize from 'quill-image-resize-module'; ``` ##### 5.2 配置 Quill 实例 通过 `options` 属性对 Quill 编辑器进行自定义配置。以下是一个完整的配置示例: ```javascript import { QuillEditor } from '@vueup/vue-quill'; import ImageDrop from 'quill-image-drop-module'; import ImageResize from 'quill-image-resize-module'; export default { components: { QuillEditor }, setup() { const editorContent = ref('<p>Hello World</p>'); const quillOptions = { modules: { toolbar: [ ['bold', 'italic', 'underline', 'strike'], // 加粗、斜体、下划线、删除线 [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表、无序列表 ['link', 'image'], // 链接、图片 ], imageDrop: true, // 启用图片拖拽功能 imageResize: {}, // 启用图片缩放功能 }, theme: 'snow', // 使用雪花主题 }; return { editorContent, quillOptions }; }, }; ``` ##### 5.3 在模板中应用配置 将 `quillOptions` 应用于 `<QuillEditor>` 组件: ```vue <template> <div> <QuillEditor v-model:content="editorContent" :options="quillOptions" contentType="html" /> </div> </template> ``` #### 6. 注意事项 - 确保安装的 `@vueup/vue-quill` 版本与 Vue3 兼容[^4]。 - 如果需要动态渲染多个 Quill 编辑器实例,建议为每个实例绑定独立的 `v-model` 数据[^4]。 - 图片上传功能可能需要额外配置后端接口支持。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值