| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- <script lang="ts" setup>/**
- * @Name: index.vue
- * @Description: 文件下载组件
- * @Author: Cheney
- */
- import dayjs from 'dayjs';
- import { type ButtonProps, ElMessage } from 'element-plus';
- const props = defineProps<Partial<Omit<ButtonProps, 'loading'>>>();
- const attrs = useAttrs() as any;
- const loading = ref(false);
- async function handleDownload() {
- loading.value = true;
- try {
- const response = await attrs.api(attrs.query);
- const blob = new Blob([ response.data ], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
- // 创建一个临时 URL
- const url = window.URL.createObjectURL(blob);
- // 创建一个临时的 <a> 元素并触发下载
- const link = document.createElement('a');
- link.href = url;
- // 设置文件名
- const currentTime = dayjs().format('YYYY-MM-DD_HH_mm_ss');
- const filename = `${ currentTime }.xlsx`;
- link.setAttribute('download', filename);
- // 添加到 body, 触发点击, 然后移除
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- // 释放 URL 对象
- window.URL.revokeObjectURL(url);
- if (response.code === 2000) ElMessage.success('文件下载成功');
- } catch (error) {
- console.error('==Error==:', error);
- ElMessage.error('文件下载失败,请重试');
- } finally {
- loading.value = false;
- }
- }
- </script>
- <template>
- <el-button :loading="loading" v-bind="props" @click="handleDownload">
- <slot></slot>
- </el-button>
- </template>
- <style scoped>
- </style>
|