优化:🔥 深度优化后端 CRUD 公共组件,并抽取前端下载功能到 CRUD 公共组件

1. 后端抽取导出功能到 CRUD 公共组件
2. 查询列表及导出接口支持排序参数
3. 深度优化 BaseServiceImpl 中的 CRUD 公共实现
4. 前端抽取公共下载组件
5. 优化部分细节并修复部分错误
This commit is contained in:
2023-02-13 21:15:06 +08:00
parent 142d315a8d
commit 03b57fb021
25 changed files with 457 additions and 307 deletions

View File

@@ -7,8 +7,8 @@ export interface DeptRecord {
deptId?: number;
deptName: string;
parentId?: number;
deptSort: number;
description?: string;
deptSort: number;
status?: number;
createUserString?: string;
createTime?: string;
@@ -24,7 +24,7 @@ export interface DeptParam {
}
export function listDept(params: DeptParam) {
return axios.get<DeptRecord[]>(`${BASE_URL}/all`, {
return axios.get<DeptRecord[]>(`${BASE_URL}/list`, {
params,
paramsSerializer: (obj) => {
return qs.stringify(obj);
@@ -47,13 +47,3 @@ export function updateDept(req: DeptRecord) {
export function deleteDept(ids: number | Array<number>) {
return axios.delete(`${BASE_URL}/${ids}`);
}
export function exportDept(params: DeptParam) {
return axios.get(`${BASE_URL}/export`, {
params,
paramsSerializer: (obj) => {
return qs.stringify(obj);
},
responseType: 'blob',
});
}

View File

@@ -0,0 +1,66 @@
import axios from 'axios';
import qs from 'query-string';
import { Notification } from '@arco-design/web-vue';
import dayjs from 'dayjs';
/**
* 下载
*
* @param url URL
* @param params 查询条件
* @param fileName 文件名
*/
export default function download(
url: string,
params: any,
fileName: string | undefined
) {
return axios
.get(url, {
params,
paramsSerializer: (obj) => {
return qs.stringify(obj);
},
responseType: 'blob',
})
.then(async (res) => {
// 获取文件名
if (!fileName) {
const contentDisposition = res.headers['content-disposition'];
const pattern = new RegExp('filename=([^;]+\\.[^\\.;]+);*');
const result = pattern.exec(contentDisposition) || '';
// 对名字进行解码
fileName = window.decodeURI(result[1]);
} else {
fileName = `${fileName}_${dayjs().format('YYYYMMDDHHmmss')}`;
}
// 创建下载的链接
const blob = new Blob([res.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
});
const downloadElement = document.createElement('a');
const href = window.URL.createObjectURL(blob);
downloadElement.style.display = 'none';
downloadElement.href = href;
// 下载后文件名
downloadElement.download = fileName;
document.body.appendChild(downloadElement);
// 点击下载
downloadElement.click();
// 下载完成,移除元素
document.body.removeChild(downloadElement);
// 释放掉 blob 对象
window.URL.revokeObjectURL(href);
})
.catch((error) => {
console.error(error);
Notification.warning({
title: '警告',
content:
"如果您正在访问演示环境,点击导出会报错。这是由于演示环境开启了 Mock.js而 Mock.js 会将 responseType 设置为 '',这不仅会导致关键判断出错,也会导致导出的文件无法打开。",
duration: 10000,
closable: true,
});
});
}

View File

@@ -13,6 +13,7 @@ import Chart from './chart/index.vue';
import Breadcrumb from './breadcrumb/index.vue';
import DateRangePicker from './date-range-picker/index.vue';
import RightToolbar from './right-toolbar/index.vue';
import download from './crud';
// Manually introduce ECharts modules to reduce packing size
@@ -31,6 +32,10 @@ use([
export default {
install(Vue: App) {
// 全局方法挂载
Vue.config.globalProperties.download = download;
// 全局组件挂载
Vue.component('Chart', Chart);
Vue.component('Breadcrumb', Breadcrumb);
Vue.component('DateRangePicker', DateRangePicker);

View File

@@ -15,8 +15,9 @@ export function encryptByMd5(txt: string) {
return md5(txt).toString();
}
const publicKey = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM51dgYtMyF+tTQt80sfFOpSV27a7t9u' +
'aUVeFrdGiVxscuizE7H8SMntYqfn9lp8a5GH5P1/GGehVjUD2gF/4kcCAwEAAQ=='
const publicKey =
'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM51dgYtMyF+tTQt80sfFOpSV27a7t9u' +
'aUVeFrdGiVxscuizE7H8SMntYqfn9lp8a5GH5P1/GGehVjUD2gF/4kcCAwEAAQ==';
export function encryptByRsa(txt: string) {
const encryptor = new JSEncrypt();

View File

@@ -1,16 +1,17 @@
import axios from "axios";
import type { AxiosRequestConfig, AxiosResponse } from "axios";
import { Message } from "@arco-design/web-vue";
import { getToken } from "@/utils/auth";
import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message } from '@arco-design/web-vue';
import { getToken } from '@/utils/auth';
// default config
if (import.meta.env.VITE_API_BASE_URL) {
axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
axios.defaults.timeout = 60000 // 1 分钟
axios.defaults.timeout = 60000; // 1 分钟
}
// request interceptors
axios.interceptors.request.use((config: AxiosRequestConfig) => {
axios.interceptors.request.use(
(config: AxiosRequestConfig) => {
const token = getToken();
if (token) {
if (!config.headers) {
@@ -35,9 +36,13 @@ export interface HttpResponse<T = unknown> {
}
// response interceptors
axios.interceptors.response.use((response: AxiosResponse<HttpResponse>) => {
axios.interceptors.response.use(
(response: AxiosResponse<HttpResponse>) => {
// 二进制数据则直接返回
if(response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer'){
if (
response.request.responseType === 'blob' ||
response.request.responseType === 'arraybuffer'
) {
return response;
}
@@ -49,7 +54,7 @@ axios.interceptors.response.use((response: AxiosResponse<HttpResponse>) => {
// 操作失败,弹出错误提示
Message.error({
content: res.msg,
duration: 3000
duration: 3000,
});
//
// if (res.code === 401) {
@@ -61,9 +66,9 @@ axios.interceptors.response.use((response: AxiosResponse<HttpResponse>) => {
console.error(`err: ${error}`);
const res = error.response.data;
Message.error({
content: res.msg || "网络错误",
duration: 3000
content: res.msg || '网络错误',
duration: 3000,
});
return Promise.reject(error);
}
);
);

View File

@@ -302,7 +302,6 @@
createDept,
updateDept,
deleteDept,
exportDept,
} from '@/api/system/dept';
import listDeptTree from '@/api/common';
@@ -341,6 +340,7 @@
queryParams: {
deptName: undefined,
status: undefined,
sort: ['parentId,asc', 'deptSort,asc', 'createTime,desc'],
},
// 表单数据
form: {} as DeptRecord,
@@ -410,8 +410,9 @@
deptId: undefined,
deptName: '',
parentId: undefined,
deptSort: 999,
description: '',
deptSort: 999,
status: 1,
};
proxy.$refs.formRef?.resetFields();
};
@@ -521,40 +522,8 @@
const handleExport = () => {
if (exportLoading.value) return;
exportLoading.value = true;
exportDept({ ...queryParams.value })
.then(async (res) => {
const blob = new Blob([res.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
});
const contentDisposition = res.headers['content-disposition'];
const pattern = new RegExp('filename=([^;]+\\.[^\\.;]+);*');
const result = pattern.exec(contentDisposition) || '';
// 对名字进行解码
const fileName = window.decodeURI(result[1]);
// 创建下载的链接
const downloadElement = document.createElement('a');
const href = window.URL.createObjectURL(blob);
downloadElement.style.display = 'none';
downloadElement.href = href;
// 下载后文件名
downloadElement.download = fileName;
document.body.appendChild(downloadElement);
// 点击下载
downloadElement.click();
// 下载完成,移除元素
document.body.removeChild(downloadElement);
// 释放掉 blob 对象
window.URL.revokeObjectURL(href);
})
.catch(() => {
proxy.$notification.warning({
title: '警告',
content:
"如果您正在访问演示环境,点击导出会报错。这是由于演示环境开启了 Mock.js而 Mock.js 会将 responseType 设置为 '',这不仅会导致关键判断出错,也会导致导出的文件无法打开。",
duration: 10000,
closable: true,
});
})
proxy
.download('/system/dept/export', { ...queryParams.value }, '部门数据')
.finally(() => {
exportLoading.value = false;
});

View File

@@ -63,6 +63,14 @@
>
<template #icon><icon-delete /></template>删除
</a-button>
<a-button
:loading="exportLoading"
type="primary"
status="warning"
@click="handleExport"
>
<template #icon><icon-download /></template>导出
</a-button>
</a-space>
</a-col>
<a-col :span="12">
@@ -383,6 +391,7 @@
const showQuery = ref(true);
const loading = ref(false);
const detailLoading = ref(false);
const exportLoading = ref(false);
const visible = ref(false);
const detailVisible = ref(false);
const statusOptions = ref<SelectOptionData[]>([
@@ -478,6 +487,7 @@
dataScopeDeptIds: undefined,
description: '',
roleSort: 999,
status: 1,
};
proxy.$refs.formRef?.resetFields();
};
@@ -580,6 +590,19 @@
multiple.value = !rowKeys.length;
};
/**
* 导出
*/
const handleExport = () => {
if (exportLoading.value) return;
exportLoading.value = true;
proxy
.download('/system/role/export', { ...queryParams.value }, '角色数据')
.finally(() => {
exportLoading.value = false;
});
};
/**
* 修改状态
*