Quellcode durchsuchen

富文本编辑器调整图片粘贴

xiaoyelj vor 10 Monaten
Ursprung
Commit
98f10fd6a7
1 geänderte Dateien mit 56 neuen und 0 gelöschten Zeilen
  1. 56 0
      src/components/Editor/index.vue

+ 56 - 0
src/components/Editor/index.vue

@@ -161,6 +161,62 @@ const handleBeforeUpload = (file: any) => {
 const handleUploadError = (err: any) => {
   proxy?.$modal.msgError('上传文件失败');
 };
+
+// 处理粘贴事件
+const handlePaste = (event: ClipboardEvent) => {
+  const clipboardData = event.clipboardData;
+  if (clipboardData) {
+    const items = Array.from(clipboardData.items);
+    for (let i = 0; i < items.length; i++) {
+      const item = items[i];
+      if (item.type.startsWith('image/')) {
+        event.preventDefault();
+        const file = item.getAsFile();
+        if (file) {
+          handleImageUpload(file);
+        }
+      }
+    }
+  }
+};
+
+const handleImageUpload = async (file: File) => {
+  const formData = new FormData();
+  formData.append('file', file);
+
+  try {
+    proxy?.$modal.loading('正在上传图片,请稍候...');
+    const response = await fetch(upload.url, {
+      method: 'POST',
+      headers: upload.headers,
+      body: formData
+    });
+    const res = await response.json();
+    if (res.code === 200) {
+      const quill = toRaw(quillEditorRef.value).getQuill();
+      const length = quill.selection.savedRange.index;
+      quill.insertEmbed(length, 'image', res.data.url);
+      quill.setSelection(length + 1);
+    } else {
+      proxy?.$modal.msgError('图片上传失败');
+    }
+  } catch (error) {
+    proxy?.$modal.msgError('图片上传失败');
+  } finally {
+    proxy?.$modal.closeLoading();
+  }
+};
+
+// 监听粘贴事件
+onMounted(() => {
+  const quill = toRaw(quillEditorRef.value).getQuill();
+  quill.root.addEventListener('paste', handlePaste);
+});
+
+onBeforeUnmount(() => {
+  const quill = toRaw(quillEditorRef.value).getQuill();
+  quill.root.removeEventListener('paste', handlePaste);
+});
 </script>
 
 <style>