feat: 🚀 tabs功能基本完成

This commit is contained in:
2025-07-23 15:42:28 +08:00
parent d79c3f8191
commit da149760cb
8 changed files with 2058 additions and 227 deletions

3
src/components.d.ts vendored
View File

@@ -62,6 +62,9 @@ declare module "vue" {
IEpSearch: typeof import("~icons/ep/search")["default"];
IEpSwitchButton: typeof import("~icons/ep/switch-button")["default"];
Index2: typeof import("./components/Editor/index2.vue")["default"];
Index3333: typeof import("./components/Editor/index3333.vue")["default"];
Index444: typeof import("./components/Editor/index444.vue")["default"];
Index5555: typeof import("./components/Editor/index5555.vue")["default"];
RouterLink: typeof import("vue-router")["RouterLink"];
RouterView: typeof import("vue-router")["RouterView"];
}

View File

@@ -1,5 +1,5 @@
<template>
<!-- 原有模板代码不变 -->
<!-- 图片上传组件 -->
<el-upload
:id="uuid"
action="#"
@@ -13,6 +13,7 @@
<i ref="uploadRef" class="Plus editor-img-uploader"></i>
</el-upload>
<!-- 视频上传组件 -->
<input
type="file"
accept="video/*"
@@ -22,9 +23,11 @@
@change="handleVideoUpload"
style="width: 0; height: 0; cursor: pointer; opacity: 0"
/>
<!-- 主富文本编辑器 -->
<div class="editor">
<QuillEditor
id="editorId"
id="mainEditor"
ref="myQuillEditor"
v-model:content="editorContent"
contentType="html"
@@ -32,58 +35,145 @@
:options="options"
/>
</div>
<!-- 标签页配置弹窗 -->
<div>
<el-dialog v-model="outerVisible" title="标签页配置" style="width: 900px; height: 900px">
<el-tabs
v-model="activeName"
type="card"
class="demo-tabs"
editable
@edit="handleTabsEdit"
@tab-change="handleTabChange"
>
<el-tab-pane :label="item.title" :name="item.title" v-for="(item, index) in tabsData" :key="index">
<!-- 标签页编辑器使用动态ref + 唯一ID -->
<QuillEditor
:id="`tabEditor_${index}`"
:ref="
el => {
if (el) tabEditors[index] = el;
}
"
v-model:content="item.content"
contentType="html"
:options="options1"
/>
</el-tab-pane>
</el-tabs>
<template #footer>
<div class="dialog-footer">
<el-button @click="outerVisible = false">取消</el-button>
<el-button type="primary" @click="handleQR"> 确认 </el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script setup name="Editor">
// 原有导入语句不变
import { QuillEditor, Quill } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import { getCurrentInstance, reactive, ref, toRaw, computed, onMounted } from "vue";
import { getCurrentInstance, reactive, ref, toRaw, computed, onMounted, nextTick } from "vue";
import { generateUUID } from "@/utils";
import { h } from "@/utils/url";
import { routerObj } from "./utils.js";
import { titleConfig } from "./titleConfig.js";
import { uploadVideo, uploadImg } from "@/api/modules/upload";
import { ElNotification } from "element-plus";
import { useRouter } from "vue-router";
// 字体配置保留
// 字体配置
let fontSizeStyle = Quill.import("attributors/style/size");
fontSizeStyle.whitelist = ["12px", "14px", "16px", "18px", "20px", "22px", "24px", "26px", "28px", "30px", "32px"];
Quill.register(fontSizeStyle, true);
// 自定义Blot保留
// 自定义Blot
import ImageBlot from "./quill-image";
import Video from "./quill-video";
import TabsBlot from "./quill-tabs";
Quill.register(Video);
Quill.register(ImageBlot);
Quill.register(TabsBlot);
// 基础变量
const { proxy } = getCurrentInstance();
const emit = defineEmits(["update:content", "handleRichTextContentChange"]);
const uuid = ref("id-" + generateUUID());
const $router = useRouter();
const routerValueName = $router.currentRoute.value.name;
const routerName = ref(routerObj[routerValueName]);
Quill.register(Video);
Quill.register(ImageBlot);
// 原有响应式变量和props保留
const { proxy } = getCurrentInstance();
const emit = defineEmits(["update:content", "handleRichTextContentChange"]);
const uploadFileVideo = ref(null);
const outerVisible = ref(false);
const imageList = ref([]);
const imageListDb = ref([]);
const tabsData = ref([]);
const activeName = ref(null);
const activeEditor = ref("main"); // 跟踪当前活跃编辑器main/tab-索引
// 标签页编辑器ref数组
const tabEditors = ref([]);
// Props
const props = defineProps({
content: { type: String, default: "" },
readOnly: { type: Boolean, default: false },
fileSizeLimit: { type: Number, default: 10 }
});
// 计算属性保留
// 主编辑器内容双向绑定
const editorContent = computed({
get: () => props.content,
set: val => {
emit("update:content", val);
}
});
const myQuillEditor = ref(null);
const myQuillEditor = ref(null); // 主编辑器ref
// 工具栏配置保留
// 主编辑器配置
const options = reactive({
theme: "snow",
debug: "warn",
modules: {
toolbar: {
container: [
["bold", "italic", "underline", "strike"],
["blockquote", "code-block"],
[{ list: "ordered" }, { list: "bullet" }],
[{ indent: "-1" }, { indent: "+1" }],
[{ size: fontSizeStyle.whitelist }],
[{ header: [1, 2, 3, 4, 5, 6, false] }],
[{ color: [] }, { background: [] }],
[{ align: [] }],
["clean"],
["link", "image", "video", "tabs"]
],
handlers: {
image: function (value) {
if (value) {
activeEditor.value = "main";
proxy.$refs.uploadRef.click();
} else Quill.format("customImage", true);
},
video: function (value) {
if (value) {
activeEditor.value = "main";
document.querySelector("#uploadFileVideo")?.click();
} else Quill.format("customVideo", true);
},
tabs: function (value) {
outerVisible.value = value;
}
}
}
},
placeholder: "请输入内容...",
readOnly: props.readOnly
});
// 标签页编辑器配置
const options1 = reactive({
theme: "snow",
debug: "warn",
modules: {
@@ -102,88 +192,46 @@ const options = reactive({
],
handlers: {
image: function (value) {
if (value) proxy.$refs.uploadRef.click();
else Quill.format("customImage", true);
if (value) {
const currentIndex = tabsData.value.findIndex(item => item.title === activeName.value);
activeEditor.value = `tab-${currentIndex}`;
proxy.$refs.uploadRef.click();
} else Quill.format("customImage", true);
},
video: function (value) {
if (value) document.querySelector("#uploadFileVideo")?.click();
else Quill.format("customVideo", true);
if (value) {
const currentIndex = tabsData.value.findIndex(item => item.title === activeName.value);
activeEditor.value = `tab-${currentIndex}`;
document.querySelector("#uploadFileVideo")?.click();
} else Quill.format("customVideo", true);
}
}
}
},
placeholder: "请输入内容...",
readOnly: props.readOnly,
clipboard: {
matchers: [
[
"img",
(node, delta) => {
const src = node.getAttribute("src");
const id = node.getAttribute("id");
delta.insert({ image: { src, id: id } });
}
]
]
}
readOnly: props.readOnly
});
// 恢复排序函数(原有代码保留)
const sortImageListByNumber = () => {
imageListDb.value.sort((a, b) => {
const getNumber = fileName => {
const match = fileName.match(/-(\d+)$/);
return match ? parseInt(match[1], 10) : 0;
};
const numA = getNumber(a.name);
const numB = getNumber(b.name);
return numA - numB;
});
};
// 上传前钩子保留(仅修复错误处理)
// 上传前校验
const handleBeforeUpload = file => {
const fileType = file.type;
file.customUid = generateUUID();
imageListDb.value.push(file);
sortImageListByNumber(); // 保留排序调用
const validTypes = [
"image/jpeg",
"image/png",
"image/gif",
"image/jpg",
"image/bmp",
"image/webp",
"video/mov",
"video/ts",
"video/mp4",
"video/avi"
];
if (validTypes.includes(fileType)) {
const isLt = file.size / 1024 / 1024 < props.fileSizeLimit;
if (!isLt) {
ElNotification({
title: "温馨提示",
message: `上传文件大小不能超过 ${props.fileSizeLimit} MB!`,
type: "warning"
});
// 仅移除当前无效文件(原有逻辑修复)
imageListDb.value = imageListDb.value.filter(item => item.customUid !== file.customUid);
return false;
}
return true;
} else {
ElNotification({
title: "温馨提示",
message: `文件格式不正确!`,
type: "warning"
});
// 仅移除当前无效文件(原有逻辑修复)
const validTypes = ["image/jpeg", "image/png", "image/gif", "image/jpg", "image/bmp", "image/webp"];
if (!validTypes.includes(fileType)) {
ElNotification({ title: "格式错误", message: "仅支持图片格式", type: "warning" });
imageListDb.value = imageListDb.value.filter(item => item.customUid !== file.customUid);
return false;
}
const isLt = file.size / 1024 / 1024 < props.fileSizeLimit;
if (!isLt) {
ElNotification({ title: "大小超限", message: `不能超过 ${props.fileSizeLimit} MB`, type: "warning" });
imageListDb.value = imageListDb.value.filter(item => item.customUid !== file.customUid);
return false;
}
return true;
};
// 图片上传(仅修复最后一张删除问题)
@@ -208,8 +256,16 @@ const handleHttpUpload = async options => {
// 检查所有文件上传完成
const allFilesUploaded = imageListDb.value.every(item => item.path);
if (allFilesUploaded) {
const rawMyQuillEditor = toRaw(myQuillEditor.value);
const quill = rawMyQuillEditor.getQuill();
let rawQuillEditor = "";
let quill = "";
if (activeEditor.value === "main") {
rawQuillEditor = toRaw(myQuillEditor.value);
quill = rawQuillEditor.getQuill();
} else {
const tabIndex = parseInt(activeEditor.value.split("-")[1]);
rawQuillEditor = toRaw(tabEditors.value[tabIndex]);
quill = rawQuillEditor.getQuill();
}
// 关键修复:插入后强制刷新编辑器选区
imageListDb.value.forEach(item => {
@@ -236,14 +292,21 @@ const handleHttpUpload = async options => {
imageListDb.value = imageListDb.value.filter(item => item.customUid !== options.file.customUid);
}
};
// 视频上传保留
const handleVideoUpload = async evt => {
if (evt.target.files.length === 0) return;
const formData = new FormData();
formData.append("video", evt.target.files[0]);
try {
let quill = toRaw(myQuillEditor.value).getQuill();
let rawQuillEditor = "";
let quill = "";
if (activeEditor.value === "main") {
rawQuillEditor = toRaw(myQuillEditor.value);
quill = rawQuillEditor.getQuill();
} else {
const tabIndex = parseInt(activeEditor.value.split("-")[1]);
rawQuillEditor = toRaw(tabEditors.value[tabIndex]);
quill = rawQuillEditor.getQuill();
}
let length = quill.selection.savedRange.index;
const { data } = await uploadVideo(formData);
quill.insertEmbed(length, "customVideo", {
@@ -255,48 +318,108 @@ const handleVideoUpload = async evt => {
console.log(error);
}
};
// // 视频上传区分tab和主富文本
// const handleVideoUpload = async evt => {
// if (evt.target.files.length === 0) return;
// const formData = new FormData();
// formData.append("video", evt.target.files[0]);
// 内容变化监听(增加选区修复)
const onContentChange = content => {
emit("handleRichTextContentChange", content);
emit("update:content", content);
console.log(content, "================content=================");
// 修复:当内容为空时确保编辑器可编辑
const rawMyQuillEditor = toRaw(myQuillEditor.value);
if (rawMyQuillEditor) {
const quill = rawMyQuillEditor.getQuill();
if (content === "") {
quill.enable(true);
quill.setSelection(0); // 强制设置光标位置
// try {
// const quill = await getCurrentQuillInstance();
// if (!quill) return;
// // 记录当前活跃编辑器类型,用于日志
// const editorType = activeEditor.value === "main" ? "主编辑器" : `标签页${activeEditor.value.split("-")[1]}`;
// console.log(`视频将插入到: ${editorType}`);
// const { data } = await uploadVideo(formData);
// const length = quill.selection.savedRange?.index || quill.getLength();
// quill.insertEmbed(length, "customVideo", {
// url: h + data.path,
// id: generateUUID()
// });
// evt.target.value = "";
// } catch (error) {
// console.error("视频上传失败:", error);
// ElNotification({ title: "上传失败", message: "视频上传出错", type: "error" });
// }
// };
// 标签页切换事件
const handleTabChange = tabTitle => {
const tabIndex = tabsData.value.findIndex(item => item.title === tabTitle);
activeEditor.value = `tab-${tabIndex}`;
console.log(`切换到标签页: ${tabTitle} (索引: ${tabIndex})`);
};
// 标签页编辑事件
const handleTabsEdit = (targetName, action) => {
console.log(action, "===action====");
if (action === "add") {
const newIndex = tabsData.value.length;
tabsData.value.push({ title: `标签${newIndex + 1}`, content: "" });
nextTick(() => {
activeName.value = `标签${newIndex + 1}`;
activeEditor.value = `tab-${newIndex}`;
});
} else if (action === "remove") {
const index = tabsData.value.findIndex(item => item.title === targetName);
tabsData.value.splice(index, 1);
tabEditors.value.splice(index, 1);
// 修正 activeEditor 索引
if (activeEditor.value.startsWith("tab-")) {
const currentTabIndex = parseInt(activeEditor.value.split("-")[1]);
if (currentTabIndex > index) {
// 若当前活跃标签页在删除项之后索引减1
activeEditor.value = `tab-${currentTabIndex - 1}`;
} else if (currentTabIndex === index) {
// 若删除的是当前活跃标签页,切换到第一个标签页
activeEditor.value = tabsData.value.length > 0 ? "tab-0" : "main";
}
}
}
};
// 原有初始化和清空方法保留
const initTitle = () => {
document.getElementsByClassName("ql-editor")[0].dataset.placeholder = "";
for (let item of titleConfig.value) {
let tip = document.querySelector(".ql-toolbar " + item.Choice);
if (tip) tip.setAttribute("title", item.title);
// 其他方法
const onContentChange = content => {
emit("handleRichTextContentChange", content);
emit("update:content", content);
};
const handleQR = () => {
const quill = toRaw(myQuillEditor.value)?.getQuill();
if (quill) {
const range = quill.getSelection(true);
quill.insertEmbed(range.index, "tabs", tabsData.value);
quill.setSelection(range.index + 1);
outerVisible.value = false;
}
};
const clearEditor = () => {
const rawMyQuillEditor = toRaw(myQuillEditor.value);
if (rawMyQuillEditor) {
const quill = rawMyQuillEditor.getQuill();
quill.setText("");
editorContent.value = "";
}
const initTitle = () => {
const editor = document.querySelector(".ql-editor");
if (editor) editor.dataset.placeholder = "";
titleConfig.value.forEach(item => {
const tip = document.querySelector(`.ql-toolbar ${item.Choice}`);
if (tip) tip.setAttribute("title", item.title);
});
};
onMounted(() => {
initTitle();
});
defineExpose({ clearEditor });
defineExpose({
clearEditor: () => {
const quill = toRaw(myQuillEditor.value)?.getQuill();
if (quill) {
quill.setText("");
editorContent.value = "";
}
}
});
</script>
<style lang="scss">
@import "./index.scss";
@@ -306,4 +429,45 @@ defineExpose({ clearEditor });
cursor: text !important;
user-select: text !important;
}
/* 标签页样式 */
.quill-tabs {
margin: 15px 0;
overflow: hidden;
border: 1px solid #dddddd;
border-radius: 4px;
}
/* 用伪元素添加图标(可替换为自己的图标) */
.ql-tabs::before {
font-size: 16px;
content: "T"; /* 用 emoji 或字体图标 */
}
.quill-tab-list {
display: flex;
background-color: #f8f9fa;
border-bottom: 1px solid #dddddd;
}
.quill-tab-button {
padding: 10px 15px;
font-weight: 500;
cursor: pointer;
background: transparent;
border: none;
transition: background-color 0.2s;
}
.quill-tab-button.active {
color: #007bff;
background-color: white;
border-bottom: 2px solid #007bff;
}
.quill-tab-content-list {
padding: 15px;
}
.quill-tab-content {
display: none;
}
.quill-tab-content.active {
display: block;
}
</style>

View File

@@ -1,5 +1,5 @@
<template>
<!-- 原有模板代码不变 -->
<!-- 图片上传组件 -->
<el-upload
:id="uuid"
action="#"
@@ -13,6 +13,7 @@
<i ref="uploadRef" class="Plus editor-img-uploader"></i>
</el-upload>
<!-- 视频上传组件 -->
<input
type="file"
accept="video/*"
@@ -22,9 +23,11 @@
@change="handleVideoUpload"
style="width: 0; height: 0; cursor: pointer; opacity: 0"
/>
<!-- 主富文本编辑器 -->
<div class="editor">
<QuillEditor
id="editorId"
id="mainEditor"
ref="myQuillEditor"
v-model:content="editorContent"
contentType="html"
@@ -32,58 +35,145 @@
:options="options"
/>
</div>
<!-- 标签页配置弹窗 -->
<div>
<el-dialog v-model="outerVisible" title="标签页配置" style="width: 900px; height: 900px">
<el-tabs
v-model="activeName"
type="card"
class="demo-tabs"
editable
@edit="handleTabsEdit"
@tab-change="handleTabChange"
>
<el-tab-pane :label="item.title" :name="item.title" v-for="(item, index) in tabsData" :key="index">
<!-- 标签页编辑器使用动态ref + 唯一ID -->
<QuillEditor
:id="`tabEditor_${index}`"
:ref="
el => {
if (el) tabEditors[index] = el;
}
"
v-model:content="item.content"
contentType="html"
:options="options1"
/>
</el-tab-pane>
</el-tabs>
<template #footer>
<div class="dialog-footer">
<el-button @click="outerVisible = false">取消</el-button>
<el-button type="primary" @click="handleQR"> 确认 </el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script setup name="Editor">
// 原有导入语句不变
import { QuillEditor, Quill } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import { getCurrentInstance, reactive, ref, toRaw, computed, onMounted } from "vue";
import { getCurrentInstance, reactive, ref, toRaw, computed, onMounted, nextTick } from "vue";
import { generateUUID } from "@/utils";
import { h } from "@/utils/url";
import { routerObj } from "./utils.js";
import { titleConfig } from "./titleConfig.js";
import { uploadVideo, uploadImg } from "@/api/modules/upload";
import { ElNotification } from "element-plus";
import { useRouter } from "vue-router";
// 字体配置保留
// 字体配置
let fontSizeStyle = Quill.import("attributors/style/size");
fontSizeStyle.whitelist = ["12px", "14px", "16px", "18px", "20px", "22px", "24px", "26px", "28px", "30px", "32px"];
Quill.register(fontSizeStyle, true);
// 自定义Blot保留
// 自定义Blot
import ImageBlot from "./quill-image";
import Video from "./quill-video";
import TabsBlot from "./quill-tabs";
Quill.register(Video);
Quill.register(ImageBlot);
Quill.register(TabsBlot);
// 基础变量
const { proxy } = getCurrentInstance();
const emit = defineEmits(["update:content", "handleRichTextContentChange"]);
const uuid = ref("id-" + generateUUID());
const $router = useRouter();
const routerValueName = $router.currentRoute.value.name;
const routerName = ref(routerObj[routerValueName]);
Quill.register(Video);
Quill.register(ImageBlot);
// 原有响应式变量和props保留
const { proxy } = getCurrentInstance();
const emit = defineEmits(["update:content", "handleRichTextContentChange"]);
const uploadFileVideo = ref(null);
const outerVisible = ref(false);
const imageList = ref([]);
const imageListDb = ref([]);
const tabsData = ref([]);
const activeName = ref(null);
const activeEditor = ref("main"); // 跟踪当前活跃编辑器main/tab-索引
// 标签页编辑器ref数组
const tabEditors = ref([]);
// Props
const props = defineProps({
content: { type: String, default: "" },
readOnly: { type: Boolean, default: false },
fileSizeLimit: { type: Number, default: 10 }
});
// 计算属性保留
// 主编辑器内容双向绑定
const editorContent = computed({
get: () => props.content,
set: val => {
emit("update:content", val);
}
});
const myQuillEditor = ref(null);
const myQuillEditor = ref(null); // 主编辑器ref
// 工具栏配置保留
// 主编辑器配置
const options = reactive({
theme: "snow",
debug: "warn",
modules: {
toolbar: {
container: [
["bold", "italic", "underline", "strike"],
["blockquote", "code-block"],
[{ list: "ordered" }, { list: "bullet" }],
[{ indent: "-1" }, { indent: "+1" }],
[{ size: fontSizeStyle.whitelist }],
[{ header: [1, 2, 3, 4, 5, 6, false] }],
[{ color: [] }, { background: [] }],
[{ align: [] }],
["clean"],
["link", "image", "video", "tabs"]
],
handlers: {
image: function (value) {
if (value) {
activeEditor.value = "main";
proxy.$refs.uploadRef.click();
} else Quill.format("customImage", true);
},
video: function (value) {
if (value) {
activeEditor.value = "main";
document.querySelector("#uploadFileVideo")?.click();
} else Quill.format("customVideo", true);
},
tabs: function (value) {
outerVisible.value = value;
}
}
}
},
placeholder: "请输入内容...",
readOnly: props.readOnly
});
// 标签页编辑器配置
const options1 = reactive({
theme: "snow",
debug: "warn",
modules: {
@@ -102,88 +192,46 @@ const options = reactive({
],
handlers: {
image: function (value) {
if (value) proxy.$refs.uploadRef.click();
else Quill.format("image", true);
if (value) {
const currentIndex = tabsData.value.findIndex(item => item.title === activeName.value);
activeEditor.value = `tab-${currentIndex}`;
proxy.$refs.uploadRef.click();
} else Quill.format("customImage", true);
},
video: function (value) {
if (value) document.querySelector("#uploadFileVideo")?.click();
else Quill.format("video", true);
if (value) {
const currentIndex = tabsData.value.findIndex(item => item.title === activeName.value);
activeEditor.value = `tab-${currentIndex}`;
document.querySelector("#uploadFileVideo")?.click();
} else Quill.format("customVideo", true);
}
}
}
},
placeholder: "请输入内容...",
readOnly: props.readOnly,
clipboard: {
matchers: [
[
"img",
(node, delta) => {
const src = node.getAttribute("src");
const id = node.getAttribute("id");
delta.insert({ image: { src, id: id } });
}
]
]
}
readOnly: props.readOnly
});
// 恢复排序函数(原有代码保留)
const sortImageListByNumber = () => {
imageListDb.value.sort((a, b) => {
const getNumber = fileName => {
const match = fileName.match(/-(\d+)$/);
return match ? parseInt(match[1], 10) : 0;
};
const numA = getNumber(a.name);
const numB = getNumber(b.name);
return numA - numB;
});
};
// 上传前钩子保留(仅修复错误处理)
// 上传前校验
const handleBeforeUpload = file => {
const fileType = file.type;
file.customUid = generateUUID();
imageListDb.value.push(file);
sortImageListByNumber(); // 保留排序调用
const validTypes = [
"image/jpeg",
"image/png",
"image/gif",
"image/jpg",
"image/bmp",
"image/webp",
"video/mov",
"video/ts",
"video/mp4",
"video/avi"
];
if (validTypes.includes(fileType)) {
const isLt = file.size / 1024 / 1024 < props.fileSizeLimit;
if (!isLt) {
ElNotification({
title: "温馨提示",
message: `上传文件大小不能超过 ${props.fileSizeLimit} MB!`,
type: "warning"
});
// 仅移除当前无效文件(原有逻辑修复)
imageListDb.value = imageListDb.value.filter(item => item.customUid !== file.customUid);
return false;
}
return true;
} else {
ElNotification({
title: "温馨提示",
message: `文件格式不正确!`,
type: "warning"
});
// 仅移除当前无效文件(原有逻辑修复)
const validTypes = ["image/jpeg", "image/png", "image/gif", "image/jpg", "image/bmp", "image/webp"];
if (!validTypes.includes(fileType)) {
ElNotification({ title: "格式错误", message: "仅支持图片格式", type: "warning" });
imageListDb.value = imageListDb.value.filter(item => item.customUid !== file.customUid);
return false;
}
const isLt = file.size / 1024 / 1024 < props.fileSizeLimit;
if (!isLt) {
ElNotification({ title: "大小超限", message: `不能超过 ${props.fileSizeLimit} MB`, type: "warning" });
imageListDb.value = imageListDb.value.filter(item => item.customUid !== file.customUid);
return false;
}
return true;
};
// 图片上传(仅修复最后一张删除问题)
@@ -208,13 +256,21 @@ const handleHttpUpload = async options => {
// 检查所有文件上传完成
const allFilesUploaded = imageListDb.value.every(item => item.path);
if (allFilesUploaded) {
const rawMyQuillEditor = toRaw(myQuillEditor.value);
const quill = rawMyQuillEditor.getQuill();
let rawQuillEditor = "";
let quill = "";
if (activeEditor.value === "main") {
rawQuillEditor = toRaw(myQuillEditor.value);
quill = rawQuillEditor.getQuill();
} else {
const tabIndex = parseInt(activeEditor.value.split("-")[1]);
rawQuillEditor = toRaw(tabEditors.value[tabIndex]);
quill = rawQuillEditor.getQuill();
}
// 关键修复:插入后强制刷新编辑器选区
imageListDb.value.forEach(item => {
const length = quill.getLength() - 1;
quill.insertEmbed(length, "image", {
quill.insertEmbed(length, "customImage", {
url: h + item.path,
id: item.serverImgId || generateUUID()
});
@@ -236,17 +292,24 @@ const handleHttpUpload = async options => {
imageListDb.value = imageListDb.value.filter(item => item.customUid !== options.file.customUid);
}
};
// 视频上传保留
const handleVideoUpload = async evt => {
if (evt.target.files.length === 0) return;
const formData = new FormData();
formData.append("video", evt.target.files[0]);
try {
let quill = toRaw(myQuillEditor.value).getQuill();
let rawQuillEditor = "";
let quill = "";
if (activeEditor.value === "main") {
rawQuillEditor = toRaw(myQuillEditor.value);
quill = rawQuillEditor.getQuill();
} else {
const tabIndex = parseInt(activeEditor.value.split("-")[1]);
rawQuillEditor = toRaw(tabEditors.value[tabIndex]);
quill = rawQuillEditor.getQuill();
}
let length = quill.selection.savedRange.index;
const { data } = await uploadVideo(formData);
quill.insertEmbed(length, "video", {
quill.insertEmbed(length, "customVideo", {
url: h + data.path,
id: generateUUID()
});
@@ -255,55 +318,155 @@ const handleVideoUpload = async evt => {
console.log(error);
}
};
// // 视频上传区分tab和主富文本
// const handleVideoUpload = async evt => {
// if (evt.target.files.length === 0) return;
// const formData = new FormData();
// formData.append("video", evt.target.files[0]);
// 内容变化监听(增加选区修复)
const onContentChange = content => {
emit("handleRichTextContentChange", content);
emit("update:content", content);
console.log(content, "================content=================");
// 修复:当内容为空时确保编辑器可编辑
const rawMyQuillEditor = toRaw(myQuillEditor.value);
if (rawMyQuillEditor) {
const quill = rawMyQuillEditor.getQuill();
if (content === "") {
quill.enable(true);
quill.setSelection(0); // 强制设置光标位置
// try {
// const quill = await getCurrentQuillInstance();
// if (!quill) return;
// // 记录当前活跃编辑器类型,用于日志
// const editorType = activeEditor.value === "main" ? "主编辑器" : `标签页${activeEditor.value.split("-")[1]}`;
// console.log(`视频将插入到: ${editorType}`);
// const { data } = await uploadVideo(formData);
// const length = quill.selection.savedRange?.index || quill.getLength();
// quill.insertEmbed(length, "customVideo", {
// url: h + data.path,
// id: generateUUID()
// });
// evt.target.value = "";
// } catch (error) {
// console.error("视频上传失败:", error);
// ElNotification({ title: "上传失败", message: "视频上传出错", type: "error" });
// }
// };
// 标签页切换事件
const handleTabChange = tabTitle => {
const tabIndex = tabsData.value.findIndex(item => item.title === tabTitle);
activeEditor.value = `tab-${tabIndex}`;
console.log(`切换到标签页: ${tabTitle} (索引: ${tabIndex})`);
};
// 标签页编辑事件
const handleTabsEdit = (targetName, action) => {
if (action === "add") {
const newIndex = tabsData.value.length;
tabsData.value.push({ title: `标签${newIndex + 1}`, content: "" });
nextTick(() => {
activeName.value = `标签${newIndex + 1}`;
activeEditor.value = `tab-${newIndex}`;
});
} else if (action === "remove") {
const index = tabsData.value.findIndex(item => item.title === targetName);
tabsData.value.splice(index, 1);
tabEditors.value.splice(index, 1);
// 修正 activeEditor 索引
if (activeEditor.value.startsWith("tab-")) {
const currentTabIndex = parseInt(activeEditor.value.split("-")[1]);
if (currentTabIndex > index) {
// 若当前活跃标签页在删除项之后索引减1
activeEditor.value = `tab-${currentTabIndex - 1}`;
} else if (currentTabIndex === index) {
// 若删除的是当前活跃标签页,切换到第一个标签页
activeEditor.value = tabsData.value.length > 0 ? "tab-0" : "main";
}
}
}
};
// 原有初始化和清空方法保留
const initTitle = () => {
document.getElementsByClassName("ql-editor")[0].dataset.placeholder = "";
for (let item of titleConfig.value) {
let tip = document.querySelector(".ql-toolbar " + item.Choice);
if (tip) tip.setAttribute("title", item.title);
// 其他方法
const onContentChange = content => {
emit("handleRichTextContentChange", content);
emit("update:content", content);
};
const handleQR = () => {
const quill = toRaw(myQuillEditor.value)?.getQuill();
if (quill) {
const range = quill.getSelection(true);
quill.insertEmbed(range.index, "tabs", tabsData.value);
quill.setSelection(range.index + 1);
outerVisible.value = false;
}
};
const clearEditor = () => {
const rawMyQuillEditor = toRaw(myQuillEditor.value);
if (rawMyQuillEditor) {
const quill = rawMyQuillEditor.getQuill();
quill.setText("");
editorContent.value = "";
}
const initTitle = () => {
const editor = document.querySelector(".ql-editor");
if (editor) editor.dataset.placeholder = "";
titleConfig.value.forEach(item => {
const tip = document.querySelector(`.ql-toolbar ${item.Choice}`);
if (tip) tip.setAttribute("title", item.title);
});
};
onMounted(() => {
initTitle();
});
defineExpose({ clearEditor });
defineExpose({
clearEditor: () => {
const quill = toRaw(myQuillEditor.value)?.getQuill();
if (quill) {
quill.setText("");
editorContent.value = "";
}
}
});
</script>
<style lang="scss">
@import "./index.scss";
// 增加编辑器内容区交互性确保删除可用
.ql-editor {
min-height: 100px; // 确保空编辑器也有点击区域
min-height: 600px; // 确保空编辑器也有点击区域
cursor: text !important;
user-select: text !important;
}
/* 标签页样式 */
.quill-tabs {
margin: 15px 0;
overflow: hidden;
border: 1px solid #dddddd;
border-radius: 4px;
}
/* 用伪元素添加图标(可替换为自己的图标) */
.ql-tabs::before {
font-size: 16px;
content: "T"; /* 用 emoji 或字体图标 */
}
.quill-tab-list {
display: flex;
background-color: #f8f9fa;
border-bottom: 1px solid #dddddd;
}
.quill-tab-button {
padding: 10px 15px;
font-weight: 500;
cursor: pointer;
background: transparent;
border: none;
transition: background-color 0.2s;
}
.quill-tab-button.active {
color: #007bff;
background-color: white;
border-bottom: 2px solid #007bff;
}
.quill-tab-content-list {
padding: 15px;
}
.quill-tab-content {
display: none;
}
.quill-tab-content.active {
display: block;
}
</style>

View File

@@ -0,0 +1,370 @@
<template>
<!-- 原有模板代码不变 -->
<el-upload
:id="uuid"
action="#"
:multiple="true"
:show-file-list="false"
:http-request="handleHttpUpload"
:before-upload="handleBeforeUpload"
class="editor-img-uploader"
accept=".jpeg,.jpg,.png,.gif"
>
<i ref="uploadRef" class="Plus editor-img-uploader"></i>
</el-upload>
<input
type="file"
accept="video/*"
name="file"
ref="uploadFileVideo"
id="uploadFileVideo"
@change="handleVideoUpload"
style="width: 0; height: 0; cursor: pointer; opacity: 0"
/>
<div class="editor">
<QuillEditor
id="editorId"
ref="myQuillEditor"
v-model:content="editorContent"
contentType="html"
@update:content="onContentChange"
:options="options"
/>
</div>
</template>
<script setup name="Editor">
// 原有导入语句不变
import { QuillEditor, Quill } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import { getCurrentInstance, reactive, ref, toRaw, computed, onMounted } from "vue";
import { generateUUID } from "@/utils";
import { h } from "@/utils/url";
import { routerObj } from "./utils.js";
import { titleConfig } from "./titleConfig.js";
import { uploadVideo, uploadImg } from "@/api/modules/upload";
import { ElNotification } from "element-plus";
// 字体配置保留
let fontSizeStyle = Quill.import("attributors/style/size");
fontSizeStyle.whitelist = ["12px", "14px", "16px", "18px", "20px", "22px", "24px", "26px", "28px", "30px", "32px"];
Quill.register(fontSizeStyle, true);
// 自定义Blot保留
import ImageBlot from "./quill-image";
import Video from "./quill-video";
import TabsBlot from "./quill-tabs";
const uuid = ref("id-" + generateUUID());
const $router = useRouter();
const routerValueName = $router.currentRoute.value.name;
const routerName = ref(routerObj[routerValueName]);
Quill.register(Video);
Quill.register(ImageBlot);
Quill.register(TabsBlot);
// 原有响应式变量和props保留
const { proxy } = getCurrentInstance();
const emit = defineEmits(["update:content", "handleRichTextContentChange"]);
const uploadFileVideo = ref(null);
const imageList = ref([]);
const imageListDb = ref([]);
const props = defineProps({
content: { type: String, default: "" },
readOnly: { type: Boolean, default: false },
fileSizeLimit: { type: Number, default: 10 }
});
// 计算属性保留
const editorContent = computed({
get: () => props.content,
set: val => {
emit("update:content", val);
}
});
const myQuillEditor = ref(null);
// 工具栏配置保留
const options = reactive({
theme: "snow",
debug: "warn",
modules: {
toolbar: {
container: [
["bold", "italic", "underline", "strike"],
["blockquote", "code-block"],
[{ list: "ordered" }, { list: "bullet" }],
[{ indent: "-1" }, { indent: "+1" }],
[{ size: fontSizeStyle.whitelist }],
[{ header: [1, 2, 3, 4, 5, 6, false] }],
[{ color: [] }, { background: [] }],
[{ align: [] }],
["clean"],
["link", "image", "video", "tabs"]
],
handlers: {
image: function (value) {
if (value) proxy.$refs.uploadRef.click();
else Quill.format("customImage", true);
},
video: function (value) {
if (value) document.querySelector("#uploadFileVideo")?.click();
else Quill.format("customVideo", true);
},
tabs: function () {
const quill = this.quill;
const range = quill.getSelection(true);
// 创建默认的双标签页结构
const tabsData = {
tabs: [
{ title: "标签 1", content: "这是第一个标签页的内容" },
{ title: "标签 2", content: "这是第二个标签页的内容" }
]
};
// 插入标签页Blot
quill.insertEmbed(range.index, "tabs", tabsData);
quill.setSelection(range.index + 1);
}
}
}
},
placeholder: "请输入内容...",
readOnly: props.readOnly,
clipboard: {
matchers: [
[
"img",
(node, delta) => {
const src = node.getAttribute("src");
const id = node.getAttribute("id");
delta.insert({ image: { src, id: id } });
}
]
]
}
});
// 恢复排序函数(原有代码保留)
const sortImageListByNumber = () => {
imageListDb.value.sort((a, b) => {
const getNumber = fileName => {
const match = fileName.match(/-(\d+)$/);
return match ? parseInt(match[1], 10) : 0;
};
const numA = getNumber(a.name);
const numB = getNumber(b.name);
return numA - numB;
});
};
// 上传前钩子保留(仅修复错误处理)
const handleBeforeUpload = file => {
const fileType = file.type;
file.customUid = generateUUID();
imageListDb.value.push(file);
sortImageListByNumber(); // 保留排序调用
const validTypes = [
"image/jpeg",
"image/png",
"image/gif",
"image/jpg",
"image/bmp",
"image/webp",
"video/mov",
"video/ts",
"video/mp4",
"video/avi"
];
if (validTypes.includes(fileType)) {
const isLt = file.size / 1024 / 1024 < props.fileSizeLimit;
if (!isLt) {
ElNotification({
title: "温馨提示",
message: `上传文件大小不能超过 ${props.fileSizeLimit} MB!`,
type: "warning"
});
// 仅移除当前无效文件(原有逻辑修复)
imageListDb.value = imageListDb.value.filter(item => item.customUid !== file.customUid);
return false;
}
return true;
} else {
ElNotification({
title: "温馨提示",
message: `文件格式不正确!`,
type: "warning"
});
// 仅移除当前无效文件(原有逻辑修复)
imageListDb.value = imageListDb.value.filter(item => item.customUid !== file.customUid);
return false;
}
};
// 图片上传(仅修复最后一张删除问题)
const handleHttpUpload = async options => {
let formData = new FormData();
formData.append("image", options.file);
imageList.value.push(options.file);
try {
const result = await uploadImg(formData, routerName.value, options.file.customUid);
if (result?.data?.code === 0) {
const { data } = result.data;
const { imgId } = result;
// 原有文件匹配逻辑保留
const fileItem = imageListDb.value.find(item => item.customUid === imgId);
if (fileItem) {
fileItem.serverImgId = imgId;
fileItem.path = data.path;
}
// 检查所有文件上传完成
const allFilesUploaded = imageListDb.value.every(item => item.path);
if (allFilesUploaded) {
const rawMyQuillEditor = toRaw(myQuillEditor.value);
const quill = rawMyQuillEditor.getQuill();
// 关键修复:插入后强制刷新编辑器选区
imageListDb.value.forEach(item => {
const length = quill.getLength() - 1;
quill.insertEmbed(length, "customImage", {
url: h + item.path,
id: item.serverImgId || generateUUID()
});
quill.setSelection(length + 1);
});
// 修复:清空数组前先保存最后一个光标位置
const finalLength = quill.getLength();
quill.setSelection(finalLength); // 确保光标在最后
imageList.value = [];
imageListDb.value = [];
}
}
} catch (error) {
console.error("图片上传失败:", error);
// 异常时清理当前文件
imageList.value = imageList.value.filter(item => item.customUid !== options.file.customUid);
imageListDb.value = imageListDb.value.filter(item => item.customUid !== options.file.customUid);
}
};
// 视频上传保留
const handleVideoUpload = async evt => {
if (evt.target.files.length === 0) return;
const formData = new FormData();
formData.append("video", evt.target.files[0]);
try {
let quill = toRaw(myQuillEditor.value).getQuill();
let length = quill.selection.savedRange.index;
const { data } = await uploadVideo(formData);
quill.insertEmbed(length, "customVideo", {
url: h + data.path,
id: generateUUID()
});
uploadFileVideo.value.value = "";
} catch (error) {
console.log(error);
}
};
// 内容变化监听(增加选区修复)
const onContentChange = content => {
emit("handleRichTextContentChange", content);
emit("update:content", content);
console.log(content, "================content=================");
// 修复:当内容为空时确保编辑器可编辑
const rawMyQuillEditor = toRaw(myQuillEditor.value);
if (rawMyQuillEditor) {
const quill = rawMyQuillEditor.getQuill();
if (content === "") {
quill.setText("");
editorContent.value = "";
quill.enable(true);
quill.setSelection(0); // 强制设置光标位置
}
}
};
// 原有初始化和清空方法保留
const initTitle = () => {
document.getElementsByClassName("ql-editor")[0].dataset.placeholder = "";
for (let item of titleConfig.value) {
let tip = document.querySelector(".ql-toolbar " + item.Choice);
if (tip) tip.setAttribute("title", item.title);
}
};
const clearEditor = () => {
const rawMyQuillEditor = toRaw(myQuillEditor.value);
if (rawMyQuillEditor) {
const quill = rawMyQuillEditor.getQuill();
quill.setText("");
editorContent.value = "";
}
};
onMounted(() => {
initTitle();
});
defineExpose({ clearEditor });
</script>
<style lang="scss">
@import "./index.scss";
// 增加编辑器内容区交互性确保删除可用
.ql-editor {
min-height: 600px; // 确保空编辑器也有点击区域
cursor: text !important;
user-select: text !important;
}
/* 标签页样式 */
.quill-tabs {
margin: 15px 0;
overflow: hidden;
border: 1px solid #dddddd;
border-radius: 4px;
}
/* 用伪元素添加图标(可替换为自己的图标) */
.ql-tabs::before {
font-size: 16px;
content: "T"; /* 用 emoji 或字体图标 */
}
.quill-tab-list {
display: flex;
background-color: #f8f9fa;
border-bottom: 1px solid #dddddd;
}
.quill-tab-button {
padding: 10px 15px;
font-weight: 500;
cursor: pointer;
background: transparent;
border: none;
transition: background-color 0.2s;
}
.quill-tab-button.active {
color: #007bff;
background-color: white;
border-bottom: 2px solid #007bff;
}
.quill-tab-content-list {
padding: 15px;
}
.quill-tab-content {
display: none;
}
.quill-tab-content.active {
display: block;
}
</style>

View File

@@ -0,0 +1,446 @@
<template>
<!-- 原有模板代码不变 -->
<el-upload
:id="uuid"
action="#"
:multiple="true"
:show-file-list="false"
:http-request="handleHttpUpload"
:before-upload="handleBeforeUpload"
class="editor-img-uploader"
accept=".jpeg,.jpg,.png,.gif"
>
<i ref="uploadRef" class="Plus editor-img-uploader"></i>
</el-upload>
<input
type="file"
accept="video/*"
name="file"
ref="uploadFileVideo"
id="uploadFileVideo"
@change="handleVideoUpload"
style="width: 0; height: 0; cursor: pointer; opacity: 0"
/>
<div class="editor">
<QuillEditor
id="editorId"
ref="myQuillEditor"
v-model:content="editorContent"
contentType="html"
@update:content="onContentChange"
:options="options"
/>
</div>
<div>
<el-dialog v-model="outerVisible" title="标签页配置" style="width: 900px; height: 900px">
<!-- 头部 -->
<div style="margin-bottom: 30px">
<el-button type="primary" @click="handleTabsClick">+添加标签</el-button>
</div>
<el-tabs v-model="activeName" type="card" class="demo-tabs" editable @edit="handleTabsEdit">
<el-tab-pane :label="item.title" :name="item.title" v-for="(item, index) in tabsData" :key="index">
<QuillEditor
id="editorId1"
ref="myQuillEditor1"
v-model:content="item.content"
contentType="html"
:options="options1"
/>
</el-tab-pane>
</el-tabs>
<template #footer>
<div class="dialog-footer">
<el-button @click="outerVisible = false">取消</el-button>
<el-button type="primary" @click="handleQR"> 确认 </el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script setup name="Editor">
// 原有导入语句不变
import { QuillEditor, Quill } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import { getCurrentInstance, reactive, ref, toRaw, computed, onMounted } from "vue";
import { generateUUID } from "@/utils";
import { h } from "@/utils/url";
import { routerObj } from "./utils.js";
import { titleConfig } from "./titleConfig.js";
import { uploadVideo, uploadImg } from "@/api/modules/upload";
import { ElNotification } from "element-plus";
// 字体配置保留
let fontSizeStyle = Quill.import("attributors/style/size");
fontSizeStyle.whitelist = ["12px", "14px", "16px", "18px", "20px", "22px", "24px", "26px", "28px", "30px", "32px"];
Quill.register(fontSizeStyle, true);
// 自定义Blot保留
import ImageBlot from "./quill-image";
import Video from "./quill-video";
import TabsBlot from "./quill-tabs";
const uuid = ref("id-" + generateUUID());
const $router = useRouter();
const routerValueName = $router.currentRoute.value.name;
const routerName = ref(routerObj[routerValueName]);
Quill.register(Video);
Quill.register(ImageBlot);
Quill.register(TabsBlot);
// 原有响应式变量和props保留
const { proxy } = getCurrentInstance();
const emit = defineEmits(["update:content", "handleRichTextContentChange"]);
const uploadFileVideo = ref(null);
const outerVisible = ref(false);
const imageList = ref([]);
const imageListDb = ref([]);
const tabsData = ref([]);
const activeName = ref(null);
const props = defineProps({
content: { type: String, default: "" },
readOnly: { type: Boolean, default: false },
fileSizeLimit: { type: Number, default: 10 }
});
// 计算属性保留
const editorContent = computed({
get: () => props.content,
set: val => {
emit("update:content", val);
}
});
const myQuillEditor = ref(null);
const myQuillEditor1 = ref(null);
// 工具栏配置保留
const options = reactive({
theme: "snow",
debug: "warn",
modules: {
toolbar: {
container: [
["bold", "italic", "underline", "strike"],
["blockquote", "code-block"],
[{ list: "ordered" }, { list: "bullet" }],
[{ indent: "-1" }, { indent: "+1" }],
[{ size: fontSizeStyle.whitelist }],
[{ header: [1, 2, 3, 4, 5, 6, false] }],
[{ color: [] }, { background: [] }],
[{ align: [] }],
["clean"],
["link", "image", "video", "tabs"]
],
handlers: {
image: function (value) {
if (value) proxy.$refs.uploadRef.click();
else Quill.format("customImage", true);
},
video: function (value) {
if (value) document.querySelector("#uploadFileVideo")?.click();
else Quill.format("customVideo", true);
},
tabs: function (value) {
outerVisible.value = value;
}
}
}
},
placeholder: "请输入内容...",
readOnly: props.readOnly,
clipboard: {
matchers: [
[
"img",
(node, delta) => {
const src = node.getAttribute("src");
const id = node.getAttribute("id");
delta.insert({ image: { src, id: id } });
}
]
]
}
});
const options1 = reactive({
theme: "snow",
debug: "warn",
modules: {
toolbar: {
container: [
["bold", "italic", "underline", "strike"],
["blockquote", "code-block"],
[{ list: "ordered" }, { list: "bullet" }],
[{ indent: "-1" }, { indent: "+1" }],
[{ size: fontSizeStyle.whitelist }],
[{ header: [1, 2, 3, 4, 5, 6, false] }],
[{ color: [] }, { background: [] }],
[{ align: [] }],
["clean"],
["link", "image", "video"]
],
handlers: {
image: function (value) {
if (value) proxy.$refs.uploadRef.click();
else Quill.format("customImage", true);
},
video: function (value) {
if (value) document.querySelector("#uploadFileVideo")?.click();
else Quill.format("customVideo", true);
}
}
}
},
placeholder: "请输入内容...",
readOnly: props.readOnly,
clipboard: {
matchers: [
[
"img",
(node, delta) => {
const src = node.getAttribute("src");
const id = node.getAttribute("id");
delta.insert({ image: { src, id: id } });
}
]
]
}
});
// 恢复排序函数(原有代码保留)
const sortImageListByNumber = () => {
imageListDb.value.sort((a, b) => {
const getNumber = fileName => {
const match = fileName.match(/-(\d+)$/);
return match ? parseInt(match[1], 10) : 0;
};
const numA = getNumber(a.name);
const numB = getNumber(b.name);
return numA - numB;
});
};
// 上传前钩子保留(仅修复错误处理)
const handleBeforeUpload = file => {
const fileType = file.type;
file.customUid = generateUUID();
imageListDb.value.push(file);
sortImageListByNumber(); // 保留排序调用
const validTypes = [
"image/jpeg",
"image/png",
"image/gif",
"image/jpg",
"image/bmp",
"image/webp",
"video/mov",
"video/ts",
"video/mp4",
"video/avi"
];
if (validTypes.includes(fileType)) {
const isLt = file.size / 1024 / 1024 < props.fileSizeLimit;
if (!isLt) {
ElNotification({
title: "温馨提示",
message: `上传文件大小不能超过 ${props.fileSizeLimit} MB!`,
type: "warning"
});
// 仅移除当前无效文件(原有逻辑修复)
imageListDb.value = imageListDb.value.filter(item => item.customUid !== file.customUid);
return false;
}
return true;
} else {
ElNotification({
title: "温馨提示",
message: `文件格式不正确!`,
type: "warning"
});
// 仅移除当前无效文件(原有逻辑修复)
imageListDb.value = imageListDb.value.filter(item => item.customUid !== file.customUid);
return false;
}
};
// 图片上传(仅修复最后一张删除问题)
const handleHttpUpload = async options => {
let formData = new FormData();
formData.append("image", options.file);
imageList.value.push(options.file);
try {
const result = await uploadImg(formData, routerName.value, options.file.customUid);
if (result?.data?.code === 0) {
const { data } = result.data;
const { imgId } = result;
// 原有文件匹配逻辑保留
const fileItem = imageListDb.value.find(item => item.customUid === imgId);
if (fileItem) {
fileItem.serverImgId = imgId;
fileItem.path = data.path;
}
// 检查所有文件上传完成
const allFilesUploaded = imageListDb.value.every(item => item.path);
if (allFilesUploaded) {
const rawMyQuillEditor = toRaw(myQuillEditor.value);
const quill = rawMyQuillEditor.getQuill();
// 关键修复:插入后强制刷新编辑器选区
imageListDb.value.forEach(item => {
const length = quill.getLength() - 1;
quill.insertEmbed(length, "customImage", {
url: h + item.path,
id: item.serverImgId || generateUUID()
});
quill.setSelection(length + 1);
});
// 修复:清空数组前先保存最后一个光标位置
const finalLength = quill.getLength();
quill.setSelection(finalLength); // 确保光标在最后
imageList.value = [];
imageListDb.value = [];
}
}
} catch (error) {
console.error("图片上传失败:", error);
// 异常时清理当前文件
imageList.value = imageList.value.filter(item => item.customUid !== options.file.customUid);
imageListDb.value = imageListDb.value.filter(item => item.customUid !== options.file.customUid);
}
};
// 视频上传保留
const handleVideoUpload = async evt => {
if (evt.target.files.length === 0) return;
const formData = new FormData();
formData.append("video", evt.target.files[0]);
try {
let quill = toRaw(myQuillEditor.value).getQuill();
let length = quill.selection.savedRange.index;
const { data } = await uploadVideo(formData);
quill.insertEmbed(length, "customVideo", {
url: h + data.path,
id: generateUUID()
});
uploadFileVideo.value.value = "";
} catch (error) {
console.log(error);
}
};
// 内容变化监听(增加选区修复)
const onContentChange = content => {
emit("handleRichTextContentChange", content);
emit("update:content", content);
// 修复:当内容为空时确保编辑器可编辑
const rawMyQuillEditor = toRaw(myQuillEditor.value);
if (rawMyQuillEditor) {
const quill = rawMyQuillEditor.getQuill();
if (content === "") {
quill.setText("");
editorContent.value = "";
quill.enable(true);
quill.setSelection(0); // 强制设置光标位置
}
}
};
// 原有初始化和清空方法保留
const initTitle = () => {
document.getElementsByClassName("ql-editor")[0].dataset.placeholder = "";
for (let item of titleConfig.value) {
let tip = document.querySelector(".ql-toolbar " + item.Choice);
if (tip) tip.setAttribute("title", item.title);
}
};
const clearEditor = () => {
const rawMyQuillEditor = toRaw(myQuillEditor.value);
if (rawMyQuillEditor) {
const quill = rawMyQuillEditor.getQuill();
quill.setText("");
editorContent.value = "";
}
};
const handleQR = () => {
const rawMyQuillEditor = toRaw(myQuillEditor.value);
const quill = rawMyQuillEditor.getQuill();
const range = quill.getSelection(true);
// // 插入标签页Blot
quill.insertEmbed(range.index, "tabs", tabsData);
quill.setSelection(range.index + 1);
};
const handleTabsClick = () => {
tabsData.value.push({ title: `标签${tabsData.value.length + 1}`, content: "" });
activeName.value = `标签${tabsData.value.length + 1}`;
};
const handleTabsEdit = values => {
let index = tabsData.value.findIndex(item => {
return (item.title = values);
});
tabsData.value.splice(index, 1);
};
onMounted(() => {
initTitle();
});
defineExpose({ clearEditor });
</script>
<style lang="scss">
@import "./index.scss";
// 增加编辑器内容区交互性确保删除可用
.ql-editor {
min-height: 600px; // 确保空编辑器也有点击区域
cursor: text !important;
user-select: text !important;
}
/* 标签页样式 */
.quill-tabs {
margin: 15px 0;
overflow: hidden;
border: 1px solid #dddddd;
border-radius: 4px;
}
/* 用伪元素添加图标(可替换为自己的图标) */
.ql-tabs::before {
font-size: 16px;
content: "T"; /* 用 emoji 或字体图标 */
}
.quill-tab-list {
display: flex;
background-color: #f8f9fa;
border-bottom: 1px solid #dddddd;
}
.quill-tab-button {
padding: 10px 15px;
font-weight: 500;
cursor: pointer;
background: transparent;
border: none;
transition: background-color 0.2s;
}
.quill-tab-button.active {
color: #007bff;
background-color: white;
border-bottom: 2px solid #007bff;
}
.quill-tab-content-list {
padding: 15px;
}
.quill-tab-content {
display: none;
}
.quill-tab-content.active {
display: block;
}
</style>

View File

@@ -0,0 +1,517 @@
<template>
<!-- 图片上传组件 -->
<el-upload
:id="uuid"
action="#"
:multiple="true"
:show-file-list="false"
:http-request="handleHttpUpload"
:before-upload="handleBeforeUpload"
class="editor-img-uploader"
accept=".jpeg,.jpg,.png,.gif"
>
<i ref="uploadRef" class="Plus editor-img-uploader"></i>
</el-upload>
<!-- 视频上传组件 -->
<input
type="file"
accept="video/*"
name="file"
ref="uploadFileVideo"
id="uploadFileVideo"
@change="handleVideoUpload"
style="width: 0; height: 0; cursor: pointer; opacity: 0"
/>
<!-- 主富文本编辑器 -->
<div class="editor">
<QuillEditor
id="editorId"
ref="myQuillEditor"
v-model:content="editorContent"
contentType="html"
@update:content="onContentChange"
:options="options"
/>
</div>
<!-- 标签页配置弹窗 -->
<div>
<el-dialog v-model="outerVisible" title="标签页配置" style="width: 900px; height: 900px">
<el-tabs
v-model="activeName"
type="card"
class="demo-tabs"
editable
@edit="handleTabsEdit"
@tab-change="handleTabChange"
>
<el-tab-pane :label="item.title" :name="item.title" v-for="(item, index) in tabsData" :key="index">
<QuillEditor
id="editorId1"
:ref="tabEditors[index]"
v-model:content="item.content"
contentType="html"
:options="options1"
/>
</el-tab-pane>
</el-tabs>
<template #footer>
<div class="dialog-footer">
<el-button @click="outerVisible = false">取消</el-button>
<el-button type="primary" @click="handleQR"> 确认 </el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script setup name="Editor">
import { QuillEditor, Quill } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import { getCurrentInstance, reactive, ref, toRaw, computed, onMounted, nextTick } from "vue";
import { generateUUID } from "@/utils";
import { h } from "@/utils/url";
import { routerObj } from "./utils.js";
import { titleConfig } from "./titleConfig.js";
import { uploadVideo, uploadImg } from "@/api/modules/upload";
import { ElNotification } from "element-plus";
import { useRouter } from "vue-router";
// 字体配置
let fontSizeStyle = Quill.import("attributors/style/size");
fontSizeStyle.whitelist = ["12px", "14px", "16px", "18px", "20px", "22px", "24px", "26px", "28px", "30px", "32px"];
Quill.register(fontSizeStyle, true);
// 自定义Blot
import ImageBlot from "./quill-image";
import Video from "./quill-video";
import TabsBlot from "./quill-tabs";
Quill.register(Video);
Quill.register(ImageBlot);
Quill.register(TabsBlot);
// 基础变量
const { proxy } = getCurrentInstance();
const emit = defineEmits(["update:content", "handleRichTextContentChange"]);
const uuid = ref("id-" + generateUUID());
const $router = useRouter();
const routerValueName = $router.currentRoute.value.name;
const routerName = ref(routerObj[routerValueName]);
const uploadFileVideo = ref(null);
const outerVisible = ref(false);
const imageList = ref([]);
const imageListDb = ref([]);
const tabsData = ref([]);
const activeName = ref(null);
const activeEditor = ref("main"); // 跟踪当前活跃编辑器main=主编辑器tab-xxx=标签页编辑器
const tabEditors = ref([]); // 标签页编辑器ref数组
// Props
const props = defineProps({
content: { type: String, default: "" },
readOnly: { type: Boolean, default: false },
fileSizeLimit: { type: Number, default: 10 }
});
// 主编辑器内容双向绑定
const editorContent = computed({
get: () => props.content,
set: val => {
emit("update:content", val);
}
});
const myQuillEditor = ref(null);
// 主编辑器配置工具栏添加activeEditor切换
const options = reactive({
theme: "snow",
debug: "warn",
modules: {
toolbar: {
container: [
["bold", "italic", "underline", "strike"],
["blockquote", "code-block"],
[{ list: "ordered" }, { list: "bullet" }],
[{ indent: "-1" }, { indent: "+1" }],
[{ size: fontSizeStyle.whitelist }],
[{ header: [1, 2, 3, 4, 5, 6, false] }],
[{ color: [] }, { background: [] }],
[{ align: [] }],
["clean"],
["link", "image", "video", "tabs"]
],
handlers: {
image: function (value) {
if (value) {
activeEditor.value = "main"; // 点击主编辑器图片按钮时切换状态
proxy.$refs.uploadRef.click();
} else Quill.format("customImage", true);
},
video: function (value) {
if (value) {
activeEditor.value = "main"; // 点击主编辑器视频按钮时切换状态
document.querySelector("#uploadFileVideo")?.click();
} else Quill.format("customVideo", true);
},
tabs: function (value) {
outerVisible.value = value;
}
}
}
},
placeholder: "请输入内容...",
readOnly: props.readOnly,
clipboard: {
matchers: [
[
"img",
(node, delta) => {
const src = node.getAttribute("src");
const id = node.getAttribute("id");
delta.insert({ image: { src, id: id } });
}
]
]
}
});
// 标签页编辑器配置工具栏添加activeEditor切换
const options1 = reactive({
theme: "snow",
debug: "warn",
modules: {
toolbar: {
container: [
["bold", "italic", "underline", "strike"],
["blockquote", "code-block"],
[{ list: "ordered" }, { list: "bullet" }],
[{ indent: "-1" }, { indent: "+1" }],
[{ size: fontSizeStyle.whitelist }],
[{ header: [1, 2, 3, 4, 5, 6, false] }],
[{ color: [] }, { background: [] }],
[{ align: [] }],
["clean"],
["link", "image", "video"]
],
handlers: {
image: function (value) {
if (value) {
// 点击标签页图片按钮时,切换到当前标签页编辑器
const currentIndex = tabsData.value.findIndex(item => item.title === activeName.value);
activeEditor.value = `tab-${currentIndex}`;
proxy.$refs.uploadRef.click();
} else Quill.format("customImage", true);
},
video: function (value) {
if (value) {
// 点击标签页视频按钮时,切换到当前标签页编辑器
const currentIndex = tabsData.value.findIndex(item => item.title === activeName.value);
activeEditor.value = `tab-${currentIndex}`;
document.querySelector("#uploadFileVideo")?.click();
} else Quill.format("customVideo", true);
}
}
}
},
placeholder: "请输入内容...",
readOnly: props.readOnly,
clipboard: {
matchers: [
[
"img",
(node, delta) => {
const src = node.getAttribute("src");
const id = node.getAttribute("id");
delta.insert({ image: { src, id: id } });
}
]
]
}
});
// 排序函数
const sortImageListByNumber = () => {
imageListDb.value.sort((a, b) => {
const getNumber = fileName => {
const match = fileName.match(/-(\d+)$/);
return match ? parseInt(match[1], 10) : 0;
};
const numA = getNumber(a.name);
const numB = getNumber(b.name);
return numA - numB;
});
};
// 上传前校验
const handleBeforeUpload = file => {
const fileType = file.type;
file.customUid = generateUUID();
imageListDb.value.push(file);
sortImageListByNumber();
const validTypes = [
"image/jpeg",
"image/png",
"image/gif",
"image/jpg",
"image/bmp",
"image/webp",
"video/mov",
"video/ts",
"video/mp4",
"video/avi"
];
if (validTypes.includes(fileType)) {
const isLt = file.size / 1024 / 1024 < props.fileSizeLimit;
if (!isLt) {
ElNotification({
title: "温馨提示",
message: `上传文件大小不能超过 ${props.fileSizeLimit} MB!`,
type: "warning"
});
imageListDb.value = imageListDb.value.filter(item => item.customUid !== file.customUid);
return false;
}
return true;
} else {
ElNotification({
title: "温馨提示",
message: `文件格式不正确!`,
type: "warning"
});
imageListDb.value = imageListDb.value.filter(item => item.customUid !== file.customUid);
return false;
}
};
// 图片上传(区分主编辑器和标签页)
const handleHttpUpload = async options => {
let formData = new FormData();
formData.append("image", options.file);
imageList.value.push(options.file);
console.log();
try {
const result = await uploadImg(formData, routerName.value, options.file.customUid);
if (result?.data?.code === 0) {
const { data } = result.data;
const { imgId } = result;
const fileItem = imageListDb.value.find(item => item.customUid === imgId);
if (fileItem) {
fileItem.serverImgId = imgId;
fileItem.path = data.path;
}
// 所有文件上传完成后插入对应编辑器
const allFilesUploaded = imageListDb.value.every(item => item.path);
if (allFilesUploaded) {
let quill;
// 区分:主编辑器上传
if (activeEditor.value === "main") {
const rawEditor = toRaw(myQuillEditor.value);
quill = rawEditor.getQuill();
}
// 标签页编辑器上传
else if (activeEditor.value.startsWith("tab-")) {
const tabIndex = parseInt(activeEditor.value.split("-")[1]);
const rawEditor = toRaw(tabEditors.value[tabIndex].value);
quill = rawEditor.getQuill();
}
if (quill) {
imageListDb.value.forEach(item => {
const length = quill.getLength() - 1;
quill.insertEmbed(length, "customImage", {
url: h + item.path,
id: item.serverImgId || generateUUID()
});
quill.setSelection(length + 1);
});
}
// 清空上传列表
imageList.value = [];
imageListDb.value = [];
}
}
} catch (error) {
console.error("图片上传失败:", error);
imageList.value = imageList.value.filter(item => item.customUid !== options.file.customUid);
imageListDb.value = imageListDb.value.filter(item => item.customUid !== options.file.customUid);
}
};
// 视频上传(区分主编辑器和标签页)
const handleVideoUpload = async evt => {
if (evt.target.files.length === 0) return;
const formData = new FormData();
formData.append("video", evt.target.files[0]);
try {
let quill;
// 区分:主编辑器上传
if (activeEditor.value === "main") {
const rawEditor = toRaw(myQuillEditor.value);
quill = rawEditor.getQuill();
}
// 标签页编辑器上传
else if (activeEditor.value.startsWith("tab-")) {
const tabIndex = parseInt(activeEditor.value.split("-")[1]);
const rawEditor = toRaw(tabEditors.value[tabIndex].value);
quill = rawEditor.getQuill();
}
if (quill) {
const length = quill.selection.savedRange.index;
const { data } = await uploadVideo(formData);
quill.insertEmbed(length, "customVideo", {
url: h + data.path,
id: generateUUID()
});
uploadFileVideo.value.value = ""; // 清空输入
}
} catch (error) {
console.log("视频上传失败:", error);
}
};
// 内容变化监听
const onContentChange = content => {
emit("handleRichTextContentChange", content);
emit("update:content", content);
const rawMyQuillEditor = toRaw(myQuillEditor.value);
if (rawMyQuillEditor) {
const quill = rawMyQuillEditor.getQuill();
if (content === "") {
quill.setText("");
editorContent.value = "";
quill.enable(true);
quill.setSelection(0);
}
}
};
// 标签页操作:添加/删除标签
const handleTabsEdit = (targetName, action) => {
if (action === "add") {
const newIndex = tabsData.value.length;
tabsData.value.push({
title: `标签${newIndex + 1}`,
content: ""
});
// 初始化标签页编辑器ref
tabEditors.value[newIndex] = ref(null);
// 切换到新标签页
nextTick(() => {
activeName.value = `标签${newIndex + 1}`;
activeEditor.value = `tab-${newIndex}`;
});
} else if (action === "remove") {
const index = tabsData.value.findIndex(item => item.title === targetName);
tabsData.value.splice(index, 1);
// 若删除当前活跃标签页,自动切换
if (activeName.value === targetName && tabsData.value.length > 0) {
activeName.value = tabsData.value[0].title;
activeEditor.value = "tab-0";
}
}
};
// 标签页切换时更新活跃编辑器
const handleTabChange = tabTitle => {
const tabIndex = tabsData.value.findIndex(item => item.title === tabTitle);
activeEditor.value = `tab-${tabIndex}`;
};
// 标签页内容插入主编辑器
const handleQR = () => {
const rawEditor = toRaw(myQuillEditor.value);
const quill = rawEditor.getQuill();
const range = quill.getSelection(true);
quill.insertEmbed(range.index, "tabs", tabsData.value);
quill.setSelection(range.index + 1);
outerVisible.value = false;
};
// 初始化工具栏标题
const initTitle = () => {
document.getElementsByClassName("ql-editor")[0].dataset.placeholder = "";
for (let item of titleConfig.value) {
let tip = document.querySelector(".ql-toolbar " + item.Choice);
if (tip) tip.setAttribute("title", item.title);
}
};
// 清空编辑器
const clearEditor = () => {
const rawEditor = toRaw(myQuillEditor.value);
if (rawEditor) {
const quill = rawEditor.getQuill();
quill.setText("");
editorContent.value = "";
}
};
// 组件挂载初始化
onMounted(() => {
initTitle();
activeEditor.value = "main"; // 默认激活主编辑器
});
defineExpose({ clearEditor });
</script>
<style lang="scss">
@import "./index.scss";
// 增加编辑器内容区交互性确保删除可用
.ql-editor {
min-height: 600px; // 确保空编辑器也有点击区域
cursor: text !important;
user-select: text !important;
}
/* 标签页样式 */
.quill-tabs {
margin: 15px 0;
overflow: hidden;
border: 1px solid #dddddd;
border-radius: 4px;
}
/* 用伪元素添加图标(可替换为自己的图标) */
.ql-tabs::before {
font-size: 16px;
content: "T"; /* 用 emoji 或字体图标 */
}
.quill-tab-list {
display: flex;
background-color: #f8f9fa;
border-bottom: 1px solid #dddddd;
}
.quill-tab-button {
padding: 10px 15px;
font-weight: 500;
cursor: pointer;
background: transparent;
border: none;
transition: background-color 0.2s;
}
.quill-tab-button.active {
color: #007bff;
background-color: white;
border-bottom: 2px solid #007bff;
}
.quill-tab-content-list {
padding: 15px;
}
.quill-tab-content {
display: none;
}
.quill-tab-content.active {
display: block;
}
</style>

View File

@@ -0,0 +1,84 @@
import { Quill } from "@vueup/vue-quill";
const BlockEmbed = Quill.import("blots/block/embed");
class TabsBlot extends BlockEmbed {
static blotName = "tabs";
static tagName = "div";
static className = "quill-tabs";
constructor(domNode) {
super(domNode);
this.bindEvents();
}
static create(value) {
const node = super.create(value);
const tabs = value;
// 标签栏
const tabList = document.createElement("div");
tabList.className = "quill-tab-list";
// 内容区
const contentList = document.createElement("div");
contentList.className = "quill-tab-content-list";
// 生成标签和内容
tabs.forEach((tab, index) => {
// 标签按钮
const btn = document.createElement("button");
btn.className = `quill-tab-button ${index === 0 ? "active" : ""}`;
btn.setAttribute("data-index", index);
btn.textContent = tab.title;
tabList.appendChild(btn);
// 内容面板
const panel = document.createElement("div");
panel.className = `quill-tab-content ${index === 0 ? "active" : ""}`;
panel.setAttribute("data-index", index);
panel.innerHTML = tab.content;
contentList.appendChild(panel);
});
node.appendChild(tabList);
node.appendChild(contentList);
node.setAttribute("contenteditable", "false"); // 禁止直接编辑容器
return node;
}
bindEvents() {
// 事件委托,确保动态生成的元素也能触发
this.domNode.addEventListener("click", e => {
const btn = e.target.closest(".quill-tab-button");
if (btn) {
e.stopPropagation();
const index = parseInt(btn.dataset.index, 10);
this.selectTab(index);
}
});
}
selectTab(index) {
const buttons = this.domNode.querySelectorAll(".quill-tab-button");
const panels = this.domNode.querySelectorAll(".quill-tab-content");
buttons.forEach((btn, i) => btn.classList.toggle("active", i === index));
panels.forEach((panel, i) => panel.classList.toggle("active", i === index));
}
static value(node) {
const tabs = [];
node.querySelectorAll(".quill-tab-button").forEach((btn, i) => {
tabs.push({
title: btn.textContent,
content: node.querySelectorAll(".quill-tab-content")[i].innerHTML
});
});
return { tabs };
}
update(mutations, context) {
super.update(mutations, context);
this.bindEvents(); // 重新绑定事件
}
}
export default TabsBlot;

View File

@@ -0,0 +1,84 @@
import { Quill } from "@vueup/vue-quill";
const BlockEmbed = Quill.import("blots/block/embed");
class TabsBlot extends BlockEmbed {
static blotName = "tabs";
static tagName = "div";
static className = "quill-tabs";
constructor(domNode) {
super(domNode);
this.bindEvents();
}
static create(value) {
const node = super.create(value);
const tabs = value;
// 标签栏
const tabList = document.createElement("div");
tabList.className = "quill-tab-list";
// 内容区
const contentList = document.createElement("div");
contentList.className = "quill-tab-content-list";
// 生成标签和内容
tabs.forEach((tab, index) => {
// 标签按钮
const btn = document.createElement("button");
btn.className = `quill-tab-button ${index === 0 ? "active" : ""}`;
btn.setAttribute("data-index", index);
btn.textContent = tab.title;
tabList.appendChild(btn);
// 内容面板
const panel = document.createElement("div");
panel.className = `quill-tab-content ${index === 0 ? "active" : ""}`;
panel.setAttribute("data-index", index);
panel.innerHTML = tab.content;
contentList.appendChild(panel);
});
node.appendChild(tabList);
node.appendChild(contentList);
node.setAttribute("contenteditable", "false"); // 禁止直接编辑容器
return node;
}
bindEvents() {
// 事件委托,确保动态生成的元素也能触发
this.domNode.addEventListener("click", e => {
const btn = e.target.closest(".quill-tab-button");
if (btn) {
e.stopPropagation();
const index = parseInt(btn.dataset.index, 10);
this.selectTab(index);
}
});
}
selectTab(index) {
const buttons = this.domNode.querySelectorAll(".quill-tab-button");
const panels = this.domNode.querySelectorAll(".quill-tab-content");
buttons.forEach((btn, i) => btn.classList.toggle("active", i === index));
panels.forEach((panel, i) => panel.classList.toggle("active", i === index));
}
static value(node) {
const tabs = [];
node.querySelectorAll(".quill-tab-button").forEach((btn, i) => {
tabs.push({
title: btn.textContent,
content: node.querySelectorAll(".quill-tab-content")[i].innerHTML
});
});
return { tabs };
}
update(mutations, context) {
super.update(mutations, context);
this.bindEvents(); // 重新绑定事件
}
}
export default TabsBlot;