重构组合式api

This commit is contained in:
WUSIJIAN
2025-11-25 17:02:31 +08:00
parent 428989c993
commit 4d6f49598e
16 changed files with 2213 additions and 1631 deletions

View File

@@ -1,244 +1,251 @@
<template>
<div class="system-edit-role-container">
<el-dialog title="" v-model="isShowDialog" width="1000px">
<el-form ref="formRef" :model="formData" :rules="rules" size="default" label-width="90px">
<el-row :gutter="35">
<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
<el-form-item label="产品名称" prop="name">
<el-input placeholder="xxx" clearable></el-input>
</el-form-item>
</el-col>
<div class="system-edit-role-container">
<el-dialog :title="(formData.id === 0 ? '添加' : '修改') + '产品'" v-model="isShowDialog" width="1000px">
<el-form ref="formRef" :model="formData" :rules="rules" size="default" label-width="90px">
<el-row :gutter="35">
<!-- 产品名称输入框 -->
<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
<el-form-item label="产品名称" prop="name">
<el-input v-model="formData.name" placeholder="请输入产品名称" clearable />
</el-form-item>
</el-col>
<!-- 新增富文本编辑器 -->
<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
<el-form-item label="产品详情" prop="content">
<Editor height="400px" placeholder="请输入产品详细描述..." />
</el-form-item>
</el-col>
<!-- 富文本编辑器 -->
<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
<el-form-item label="产品详情" prop="content">
<Editor v-model="formData.content" height="400px" placeholder="请输入产品详细描述..." />
</el-form-item>
</el-col>
</el-row>
</el-form>
</el-row>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="onCancel" size="default"> </el-button>
<el-button type="primary" @click="onSubmit" size="default" :loading="loading">{{ formData.id === 0 ? '新 增' :
'修改' }}</el-button>
</span>
</template>
</el-dialog>
</div>
<!-- 对话框底部按钮 -->
<template #footer>
<span class="dialog-footer">
<el-button @click="onCancel" size="default"> </el-button>
<el-button type="primary" @click="onSubmit" size="default" :loading="loading">
{{ formData.id === 0 ? '新 增' : '修 改' }}
</el-button>
</span>
</template>
</el-dialog>
</div>
</template>
<script lang="ts">
import { reactive, toRefs, defineComponent, ref, getCurrentInstance, unref, } from 'vue';
import { addRole, editRole, getRole, getRoleParams } from "/@/api/system/role";
import { ElMessage } from "element-plus";
import { refreshBackEndControlRoutes } from "/@/router/backEnd";
// 引入富文本编辑器组件
<script lang="ts" setup>
import { ref, reactive, toRefs, nextTick } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { addRole, editRole, getRole } from '/@/api/system/role';
import Editor from '/@/components/editor/index.vue';
// 定义接口来定义对象的类型
interface MenuDataTree {
id: number;
pid: number;
title: string;
children?: MenuDataTree[];
}
interface DialogRow {
id: number;
name: string;
status: number;
listOrder: number;
remark: string;
menuIds: Array<number>
}
interface RoleState {
loading: boolean;
isShowDialog: boolean;
formData: DialogRow;
menuData: Array<MenuDataTree>;
menuExpand: boolean;
menuNodeAll: boolean;
menuCheckStrictly: boolean;
menuProps: {
children: string;
label: string;
};
rules: object;
/**
* 产品表单数据接口
*/
interface ProductFormData {
id: number; // 产品ID
name: string; // 产品名称
status: number; // 状态1-启用0-禁用
listOrder: number; // 排序
remark: string; // 备注
content?: string; // 产品详情(富文本内容)
}
export default defineComponent({
name: 'systemEditRole',
components: {
Editor // 注册富文本组件
},
setup(props, { emit }) {
const { proxy } = getCurrentInstance() as any;
const formRef = ref<HTMLElement | null>(null);
const menuRef = ref();
const state = reactive<RoleState>({
loading: false,
isShowDialog: false,
formData: {
id: 0,
name: '',
status: 1,
listOrder: 0,
remark: '',
menuIds: []
},
// 表单校验
rules: {
name: [
{ required: true, message: "角色名称不能为空", trigger: "blur" },
]
},
menuData: [],
menuExpand: false,
menuNodeAll: false,
menuCheckStrictly: false,
menuProps: {
children: 'children',
label: 'title',
},
});
// 打开弹窗
const openDialog = (row?: DialogRow) => {
resetForm();
getMenuData();
if (row) {
getRole(row.id).then((res: any) => {
if (res.data.role) {
state.formData = res.data.role;
state.formData.menuIds = res.data.menuIds ?? []
}
})
}
state.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
state.isShowDialog = false;
};
// 取消
const onCancel = () => {
closeDialog();
};
// 新增
const onSubmit = () => {
const formWrap = unref(formRef) as any;
if (!formWrap) return;
formWrap.validate((valid: boolean) => {
if (valid) {
state.loading = true;
state.formData.menuIds = getMenuAllCheckedKeys();
if (state.formData.id === 0) {
//添加
addRole(state.formData).then(() => {
ElMessage.success('角色添加成功');
closeDialog(); // 关闭弹窗
resetMenuSession()
emit('getRoleList')
}).finally(() => {
state.loading = false;
})
} else {
//修改
editRole(state.formData).then(() => {
ElMessage.success('角色修改成功');
closeDialog(); // 关闭弹窗
resetMenuSession()
emit('getRoleList')
}).finally(() => {
state.loading = false;
})
}
}
});
};
// 获取菜单结构数据
const getMenuData = () => {
getRoleParams().then((res: any) => {
state.menuData = proxy.handleTree(res.data.menu, "id", "pid");
})
};
const resetForm = () => {
state.menuCheckStrictly = false;
state.menuExpand = false;
state.menuNodeAll = false;
state.formData = {
id: 0,
name: '',
status: 1,
listOrder: 0,
remark: '',
menuIds: []
}
};
/** 树权限(展开/折叠)*/
const handleCheckedTreeExpand = (value: any) => {
let treeList = state.menuData;
for (let i = 0; i < treeList.length; i++) {
menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
}
}
/**
* 组件状态接口
*/
interface ComponentState {
loading: boolean; // 提交加载状态
isShowDialog: boolean; // 对话框显示状态
formData: ProductFormData; // 表单数据
}
/** 树权限(全选/全不选) */
const handleCheckedTreeNodeAll = (value: any) => {
menuRef.value.setCheckedNodes(value ? state.menuData : []);
}
// 定义组件事件
const emit = defineEmits<{
/**
* 获取产品列表事件 - 用于刷新父组件列表
*/
(e: 'getRoleList'): void;
}>();
/** 树权限(父子联动) */
const handleCheckedTreeConnect = (value: any) => {
state.menuCheckStrictly = value ? true : false;
}
// 响应式状态
const state = reactive<ComponentState>({
loading: false,
isShowDialog: false,
formData: {
id: 0,
name: '',
status: 1,
listOrder: 0,
remark: '',
content: '',
},
});
/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
// 目前被选中的菜单节点
let checkedKeys = menuRef.value.getCheckedKeys();
// 半选中的菜单节点
let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
return checkedKeys;
}
// 表单验证规则
const rules: FormRules = {
name: [
{ required: true, message: '产品名称不能为空', trigger: 'blur' },
{ min: 2, max: 50, message: '产品名称长度在 2 到 50 个字符', trigger: 'blur' },
],
content: [{ required: true, message: '产品详情不能为空', trigger: 'blur' }],
};
// 重置菜单session
const resetMenuSession = () => {
refreshBackEndControlRoutes();
};
return {
openDialog,
closeDialog,
onCancel,
onSubmit,
menuRef,
formRef,
handleCheckedTreeExpand,
handleCheckedTreeNodeAll,
handleCheckedTreeConnect,
resetMenuSession,
...toRefs(state),
};
},
// 模板引用
const formRef = ref<FormInstance>();
// 解构状态数据,便于模板使用
const { loading, isShowDialog, formData } = toRefs(state);
/**
* 打开对话框
* @param row - 可选的编辑数据,如果传入则为编辑模式,否则为新增模式
*/
const openDialog = async (row?: ProductFormData) => {
// 重置表单
resetForm();
try {
if (row && row.id) {
// 编辑模式:获取产品详情
await handleEditMode(row.id);
}
// 显示对话框
state.isShowDialog = true;
} catch (error) {
console.error('打开对话框失败:', error);
ElMessage.error('初始化数据失败');
}
};
/**
* 处理编辑模式的数据获取
* @param id - 产品ID
*/
const handleEditMode = async (id: number) => {
try {
const res = await getRole(id);
if (res.data?.role) {
// 填充表单数据
state.formData = {
...res.data.role,
content: res.data.role.content || '',
};
}
} catch (error) {
console.error('获取产品详情失败:', error);
throw new Error('获取产品详情失败');
}
};
/**
* 关闭对话框
*/
const closeDialog = () => {
state.isShowDialog = false;
};
/**
* 取消操作
*/
const onCancel = () => {
closeDialog();
};
/**
* 提交表单
*/
const onSubmit = async () => {
if (!formRef.value) {
ElMessage.error('表单引用不存在');
return;
}
try {
// 表单验证
const valid = await formRef.value.validate();
if (!valid) {
ElMessage.warning('请完善表单信息');
return;
}
// 设置加载状态
state.loading = true;
// 根据ID判断是新增还是修改
if (state.formData.id === 0) {
// 新增产品
await addRole(state.formData);
ElMessage.success('产品添加成功');
} else {
// 修改产品
await editRole(state.formData);
ElMessage.success('产品修改成功');
}
// 关闭对话框并刷新列表
closeDialog();
emit('getRoleList');
} catch (error) {
console.error('提交失败:', error);
ElMessage.error(state.formData.id === 0 ? '添加失败' : '修改失败');
} finally {
state.loading = false;
}
};
/**
* 重置表单
*/
const resetForm = () => {
// 重置表单数据
state.formData = {
id: 0,
name: '',
status: 1,
listOrder: 0,
remark: '',
content: '',
};
// 在下一个DOM更新周期后清除表单验证
nextTick(() => {
formRef.value?.clearValidate();
});
};
// 暴露方法给父组件使用
defineExpose({
/**
* 打开对话框方法
*/
openDialog,
/**
* 关闭对话框方法
*/
closeDialog,
});
</script>
<style scoped lang="scss">
.tree-border {
margin-top: 5px;
border: 1px solid #e5e6e7 !important;
border-radius: 4px;
.system-edit-role-container {
// 对话框内容区域样式
:deep(.el-dialog__body) {
padding: 20px;
}
// 底部按钮区域样式
.dialog-footer {
display: flex;
justify-content: flex-end;
align-items: center;
gap: 10px;
}
}
.system-edit-role-container {
.menu-data-tree {
border: var(--el-input-border, var(--el-border-base));
border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
padding: 5px;
}
// 间距工具类
.mb20 {
margin-bottom: 20px;
}
</style>

View File

@@ -9,40 +9,36 @@
</el-dialog>
</template>
<script lang="ts">
import { defineComponent, ref, reactive } from 'vue';
<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
export default defineComponent({
name: 'ExportDialog',
setup() {
const isShowDialog = ref(false);
const tableData = ref([]);
const isShowDialog = ref(false);
const tableData = ref([]);
const form = reactive({
exportType: 'current',
fileType: 'xlsx',
});
const form = reactive({
exportType: 'current',
fileType: 'xlsx',
});
// 打开对话框
const openDialog = (data: any) => {
tableData.value = data;
isShowDialog.value = true;
};
// 打开对话框
const openDialog = (data: any) => {
tableData.value = data;
isShowDialog.value = true;
};
// 处理导出
const handleExport = () => {
// 这里处理导出逻辑
ElMessage.success('导出成功');
isShowDialog.value = false;
};
// 处理导出
const handleExport = () => {
// 这里处理导出逻辑
ElMessage.success('导出成功');
isShowDialog.value = false;
};
return {
isShowDialog,
form,
openDialog,
handleExport,
};
},
// 暴露方法给父组件使用
defineExpose({
/**
* 打开对话框方法
*/
openDialog,
});
</script>

View File

@@ -1,21 +1,7 @@
<template>
<el-dialog title="导入产品" v-model="isShowDialog" width="500px" destroy-on-close>
<el-dialog title="导入产品" v-model="isShowDialog" width="500px" destroy-on-close @close="handleDialogClose">
<div class="import-container">
<!-- 导入说明 -->
<div class="import-instructions mt20" style="margin-bottom: 40px">
<el-card shadow="never" class="box-card">
<el-text type="info" size="small">
<ul class="instruction-list">
<li>1. 请先下载模板ZIP包查看Word文档格式要求</li>
<li>2. 按照模板中的Word文档格式准备您的产品文档</li>
<li>3. 将您的Word文档打包成ZIP格式上传</li>
<li>4. 支持 .docx 格式的Word文档</li>
</ul>
</el-text>
</el-card>
</div>
<!-- 上传区域 -->
<!-- 文件上传区域 -->
<el-upload
ref="uploadRef"
class="upload-demo"
@@ -25,38 +11,49 @@
:data="uploadData"
:accept="acceptFileTypes"
:limit="1"
:on-success="handleSuccess"
:on-error="handleError"
:on-success="handleUploadSuccess"
:on-error="handleUploadError"
:before-upload="beforeUpload"
:on-exceed="handleExceed"
:on-remove="handleRemove"
>
<div class="el-upload-area">
<el-icon class="el-icon--upload"><ele-UploadFilled /></el-icon>
<el-icon class="el-icon--upload">
<UploadFilled />
</el-icon>
<div class="el-upload__text">将ZIP文件拖到此处<em>点击上传</em></div>
</div>
<template #tip>
<div class="el-upload__tip">
<el-text type="info" size="small"> 请上传 {{ acceptFileTypes }} 格式文件且不超过 {{ fileSizeLimit }}MB </el-text>
</div>
</template>
</el-upload>
<!-- 下载模板按钮 -->
<div class="download-section" style="margin-top: 20px; text-align: center">
<el-button type="primary" size="default" :loading="downloadLoading" @click="downloadTemplate" style="width: 200px">
<template #icon>
<el-icon><ele-Download /></el-icon>
</template>
{{ downloadLoading ? '正在生成模板...' : '下载导入模板' }}
</el-button>
<!-- 导入说明 -->
<div class="import-instructions mt20">
<el-card shadow="never" class="box-card">
<el-text type="info" size="small">
<ul class="instruction-list">
<li>1. 请先下载模板ZIP包查看Word文档格式要求</li>
<li>2. 按照模板中的Word文档格式准备您的产品文档</li>
<li>3. 将您的Word文档打包成ZIP格式上传</li>
<li>4. 支持 .docx 格式的Word文档</li>
<li>5. 文件大小不能超过 {{ fileSizeLimit }}MB</li>
</ul>
</el-text>
</el-card>
</div>
</div>
<template #footer>
<span class="dialog-footer">
<el-button @click="isShowDialog = false">取消</el-button>
<el-button type="primary" :loading="loading" @click="submitUpload">
<!-- 下载模板按钮 -->
<el-button type="primary" size="default" :loading="downloadLoading" @click="handleDownloadTemplate" class="download-btn">
<template #icon>
<el-icon><Download /></el-icon>
</template>
{{ downloadLoading ? '生成中...' : '下载模板' }}
</el-button>
<el-button @click="handleCancel">取消</el-button>
<el-button type="primary" :loading="loading" @click="handleSubmitUpload">
{{ loading ? '导入中...' : '开始导入' }}
</el-button>
</span>
@@ -64,80 +61,42 @@
</el-dialog>
</template>
<script lang="ts">
import { defineComponent, ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
<script lang="ts" setup>
import { ref, reactive, nextTick } from 'vue';
import { ElMessage, ElMessageBox, type UploadInstance } from 'element-plus';
import { UploadFilled, Download } from '@element-plus/icons-vue';
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
export default defineComponent({
name: 'ImportDialog',
components: { UploadFilled, Download },
emits: ['getRoleList'],
setup(props, { emit }) {
const isShowDialog = ref(false);
const uploadRef = ref();
const loading = ref(false);
const downloadLoading = ref(false);
// 定义组件事件
const emit = defineEmits<{
/**
* 获取产品列表事件 - 导入成功后刷新列表
*/
(e: 'getRoleList'): void;
}>();
// 上传配置
const uploadAction = ref('/api/product/import-word-zip');
const uploadHeaders = reactive({
Authorization: 'Bearer ' + localStorage.getItem('token'),
});
const uploadData = reactive({
type: 'word-zip',
});
const acceptFileTypes = '.zip,.ZIP';
const fileSizeLimit = 50;
// 响应式状态
const isShowDialog = ref(false);
const loading = ref(false);
const downloadLoading = ref(false);
const uploadRef = ref<UploadInstance>();
// 打开对话框
const openDialog = () => {
isShowDialog.value = true;
loading.value = false;
downloadLoading.value = false;
if (uploadRef.value) {
uploadRef.value.clearFiles();
}
};
// 上传配置
const uploadAction = '/api/product/import-word-zip';
const uploadHeaders = reactive({
Authorization: `Bearer ${localStorage.getItem('token') || ''}`,
});
const uploadData = reactive({
type: 'word-zip',
});
const acceptFileTypes = '.zip,.ZIP';
const fileSizeLimit = 50;
// 创建Word文档的二进制内容模拟真实的.docx格式
const createWordDocumentContent = (content: string) => {
// Word文档的基本结构简化版
// 实际Word文档是复杂的XML结构这里创建一个简单的文本文件
// 在实际项目中应该使用后端生成真正的Word文档
// 创建一个包含基本Word文档结构的文本
const wordContent = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?mso-application progid="Word.Document"?>
<w:wordDocument xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml">
<w:body>
<w:p>
<w:r>
<w:t>${content.replace(/\n/g, '</w:t></w:r></w:p><w:p><w:r><w:t>')}</w:t>
</w:r>
</w:p>
</w:body>
</w:wordDocument>`;
return new Blob([wordContent], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
};
// 创建文本文件内容
const createTextFile = (content: string) => {
return new Blob([content], { type: 'text/plain;charset=utf-8' });
};
// 下载模板 - 修复版本生成包含真实文件的ZIP包
const downloadTemplate = async () => {
downloadLoading.value = true;
try {
const zip = new JSZip();
// 1. 创建产品说明书模板内容
const manualContent = `产品说明书模板
// 模板内容定义
const templateContents = {
/** 产品说明书模板内容 */
manual: `产品说明书模板
产品名称_________________________
产品型号_________________________
@@ -166,10 +125,10 @@ ___________________________________
注意事项:
• ________________________________
• ________________________________
• ________________________________`;
• ________________________________`,
// 2. 创建技术规格书模板内容
const specContent = `技术规格书模板
/** 技术规格书模板内容 */
spec: `技术规格书模板
产品名称_________________________
产品型号_________________________
@@ -193,19 +152,19 @@ ___________________________________
4. 安全标准
- 认证_______________________
- 防护等级___________________`;
- 防护等级___________________`,
// 3. 创建使用说明文档
const readmeContent = `产品文档导入模板使用说明
/** 使用说明文档内容 */
readme: `产品文档导入模板使用说明
================================
欢迎使用产品文档导入模板!
📁 ZIP包内容说明
-----------------
1. 产品说明书模板.docx - 产品详细说明文档模板
2. 技术规格书模板.docx - 技术参数文档模板
3. 使用说明.txt - 本说明文件
1. 产品说明书模板.docx - 产品详细说明文档模板
2. 技术规格书模板.docx - 技术参数文档模板
3. 使用说明.txt - 本说明文件
📝 使用步骤:
-----------
@@ -227,167 +186,207 @@ ___________________________________
-----------
如有问题请联系系统管理员。
祝您使用愉快!`;
祝您使用愉快!`,
};
// 创建真实的文件Blob对象
const manualBlob = createWordDocumentContent(manualContent);
const specBlob = createWordDocumentContent(specContent);
const readmeBlob = createTextFile(readmeContent);
/**
* 创建Word文档的二进制内容
* @param content - 文档内容
* @returns Blob对象
*/
const createWordDocumentContent = (content: string): Blob => {
// 简化的Word文档XML结构
const wordContent = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?mso-application progid="Word.Document"?>
<w:wordDocument xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml">
<w:body>
<w:p>
<w:r>
<w:t>${content.replace(/\n/g, '</w:t></w:r></w:p><w:p><w:r><w:t>')}</w:t>
</w:r>
</w:p>
</w:body>
</w:wordDocument>`;
// 将文件添加到ZIP包
zip.file('产品说明书模板.docx', manualBlob);
zip.file('技术规格书模板.docx', specBlob);
zip.file('使用说明.txt', readmeBlob);
return new Blob([wordContent], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
});
};
// 生成ZIP包
const zipBlob = await zip.generateAsync({
type: 'blob',
compression: 'DEFLATE',
compressionOptions: {
level: 6,
},
});
/**
* 创建文本文件内容
* @param content - 文本内容
* @returns Blob对象
*/
const createTextFile = (content: string): Blob => {
return new Blob([content], { type: 'text/plain;charset=utf-8' });
};
// 重要:检查文件大小,确保不是空文件
if (zipBlob.size === 0) {
throw new Error('生成的ZIP包为空请检查文件内容');
}
/**
* 打开对话框
*/
const openDialog = () => {
isShowDialog.value = true;
loading.value = false;
downloadLoading.value = false;
// 下载文件
saveAs(zipBlob, `产品文档导入模板_${new Date().toISOString().split('T')[0]}.zip`);
// 清空已上传的文件
nextTick(() => {
uploadRef.value?.clearFiles();
});
};
ElMessage.success({
message: `模板下载成功!文件大小:${(zipBlob.size / 1024).toFixed(2)}KB`,
duration: 3000,
});
/**
* 处理对话框关闭
*/
const handleDialogClose = () => {
// 清空上传文件
uploadRef.value?.clearFiles();
};
// 显示使用提示
setTimeout(() => {
ElMessage.info('下载完成后请解压ZIP包查看Word文档模板');
}, 1000);
} catch (error) {
console.error('模板下载失败:', error);
ElMessage.error({
message: '模板生成失败:' + (error instanceof Error ? error.message : '未知错误'),
duration: 5000,
});
/**
* 取消操作
*/
const handleCancel = () => {
isShowDialog.value = false;
};
// 提供备用方案
setTimeout(() => {
ElMessageBox.alert('如果模板下载仍有问题,请联系管理员获取手动模板文件。', '下载失败', {
confirmButtonText: '确定',
type: 'warning',
});
}, 1000);
} finally {
downloadLoading.value = false;
}
};
/**
* 下载模板文件
*/
const handleDownloadTemplate = async () => {
downloadLoading.value = true;
// 上传前校验
const beforeUpload = (file: File) => {
const isZip = file.type === 'application/zip' || file.name.toLowerCase().endsWith('.zip');
const isLt50M = file.size / 1024 / 1024 < fileSizeLimit;
try {
const zip = new JSZip();
if (!isZip) {
ElMessage.error('请上传ZIP格式的压缩包文件!');
return false;
}
if (!isLt50M) {
ElMessage.error(`ZIP文件大小不能超过${fileSizeLimit}MB!`);
return false;
}
// 添加模板文件到ZIP包
zip.file('产品说明书模板.docx', createWordDocumentContent(templateContents.manual));
zip.file('技术规格书模板.docx', createWordDocumentContent(templateContents.spec));
zip.file('使用说明.txt', createTextFile(templateContents.readme));
ElMessage.info(`开始上传ZIP包: ${file.name} (${(file.size / 1024 / 1024).toFixed(2)}MB)`);
return true;
};
// 生成ZIP包
const zipBlob = await zip.generateAsync({
type: 'blob',
compression: 'DEFLATE',
compressionOptions: { level: 6 },
});
// 文件超出限制
const handleExceed = () => {
ElMessage.warning('只能上传一个ZIP包文件请先删除当前文件');
};
// 检查文件大小
if (zipBlob.size === 0) {
throw new Error('生成的ZIP包为空');
}
// 移除文件
const handleRemove = () => {
// 文件被移除时的处理
};
// 下载文件
const dateString = new Date().toISOString().split('T')[0];
saveAs(zipBlob, `产品文档导入模板_${dateString}.zip`);
// 上传成功
const handleSuccess = (response: any) => {
loading.value = false;
if (response.code === 200) {
ElMessage.success('Word文档导入成功');
emit('getRoleList');
isShowDialog.value = false;
} else {
ElMessage.error(response.msg || 'Word文档ZIP包导入失败');
}
};
ElMessage.success(`模板下载成功!文件大小:${(zipBlob.size / 1024).toFixed(2)}KB`);
} catch (error) {
console.error('模板下载失败:', error);
ElMessage.error(`模板生成失败:${error instanceof Error ? error.message : '未知错误'}`);
} finally {
downloadLoading.value = false;
}
};
// 上传失败
const handleError = (error: any) => {
loading.value = false;
ElMessage.error('ZIP包上传失败请重试');
console.error('ZIP upload error:', error);
};
/**
* 上传前校验
* @param file - 上传的文件
* @returns 是否允许上传
*/
const beforeUpload = (file: File): boolean => {
const isZip = file.type === 'application/zip' || file.name.toLowerCase().endsWith('.zip');
const isLtLimit = file.size / 1024 / 1024 < fileSizeLimit;
// 手动提交上传
const submitUpload = () => {
if (!uploadRef.value || !uploadRef.value.uploadFiles.length) {
ElMessage.warning('请先选择要上传的ZIP包文件');
return;
}
if (!isZip) {
ElMessage.error('请上传ZIP格式的压缩包文件!');
return false;
}
ElMessageBox.confirm('确认导入选中的ZIP包吗', '导入确认', {
confirmButtonText: '确认导入',
cancelButtonText: '取消',
type: 'warning',
})
.then(() => {
loading.value = true;
uploadRef.value.submit();
})
.catch(() => {
// 用户取消
});
};
if (!isLtLimit) {
ElMessage.error(`文件大小不能超过${fileSizeLimit}MB!`);
return false;
}
return {
isShowDialog,
uploadRef,
loading,
downloadLoading,
uploadAction,
uploadHeaders,
uploadData,
acceptFileTypes,
fileSizeLimit,
openDialog,
downloadTemplate,
beforeUpload,
handleExceed,
handleRemove,
handleSuccess,
handleError,
submitUpload,
};
},
ElMessage.info(`开始上传: ${file.name} (${(file.size / 1024 / 1024).toFixed(2)}MB)`);
return true;
};
/**
* 处理文件超出限制
*/
const handleExceed = () => {
ElMessage.warning('只能上传一个文件,请先删除当前文件');
};
/**
* 处理文件移除
*/
const handleRemove = () => {
// 文件移除后的清理操作
};
/**
* 处理上传成功
* @param response - 服务器响应
*/
const handleUploadSuccess = (response: any) => {
loading.value = false;
if (response.code === 200) {
ElMessage.success('文件导入成功');
emit('getRoleList');
isShowDialog.value = false;
} else {
ElMessage.error(response.msg || '文件导入失败');
}
};
/**
* 处理上传失败
* @param error - 错误信息
*/
const handleUploadError = (error: any) => {
loading.value = false;
ElMessage.error('文件上传失败,请重试');
console.error('Upload error:', error);
};
/**
* 手动提交上传
*/
const handleSubmitUpload = async () => {
if (!uploadRef.value?.uploadFiles?.length) {
ElMessage.warning('请先选择要上传的文件');
return;
}
try {
await ElMessageBox.confirm('确认导入选中的文件吗?', '导入确认', {
confirmButtonText: '确认导入',
cancelButtonText: '取消',
type: 'warning',
});
loading.value = true;
uploadRef.value.submit();
} catch {
// 用户取消操作
}
};
// 暴露方法给父组件
defineExpose({
openDialog,
});
</script>
<style scoped>
<style scoped lang="scss">
.import-container {
padding: 10px 0;
}
.download-section {
text-align: center;
}
.template-tips {
margin-top: 10px;
}
.upload-demo {
width: 100%;
}
@@ -403,18 +402,37 @@ ___________________________________
margin-bottom: 16px;
}
.import-instructions .card-header {
font-weight: 600;
.import-instructions {
.mt20 {
margin-top: 20px;
}
}
.instruction-list {
margin: 0;
padding-left: 16px;
line-height: 1.8;
li {
margin-bottom: 4px;
}
}
.instruction-list li {
margin-bottom: 4px;
.dialog-footer {
display: flex;
justify-content: right;
align-items: center;
.download-btn {
background-color: coral;
border-color: coral;
width: 120px;
&:hover {
background-color: #ff7f50;
border-color: #ff7f50;
}
}
}
:deep(.el-upload-dragger) {