当前位置: 首页 > news >正文

element组件封装

1.上传组件

<!--文件上传组件-->
<template><div class="upload-file"><el-uploadref="fileUpload"v-if="props.type === 'default'":action="baseURL + other.adaptationUrl(props.uploadFileUrl)":before-upload="handleBeforeUpload":file-list="fileList":headers="headers":limit="limit":on-error="handleUploadError":on-remove="handleRemove":on-preview="handlePreview":data="formData":auto-upload="autoUpload":on-success="handleUploadSuccess"class="upload-file-uploader"dragmultiple><i class="el-icon-upload"></i><div class="el-upload__text">{{ $t('excel.operationNotice') }}<em>{{ $t('excel.clickUpload') }}</em></div><template #tip><div class="el-upload__tip" v-if="props.isShowTip">{{ $t('excel.pleaseUpload') }}<template v-if="props.fileSize">{{ $t('excel.size') }} <b style="color: #f56c6c">{{ props.fileSize }}MB</b></template><template v-if="props.fileType">{{ $t('excel.format') }} <b style="color: #f56c6c">{{ props.fileType.join('/') }}</b></template>{{ $t('excel.file') }}</div></template></el-upload><el-uploadref="fileUpload"v-if="props.type === 'simple'":action="baseURL + other.adaptationUrl(props.uploadFileUrl)":before-upload="handleBeforeUpload":file-list="fileList":headers="headers":limit="limit":auto-upload="autoUpload":on-error="handleUploadError":on-remove="handleRemove":data="formData":on-success="handleUploadSuccess"class="upload-file-uploader"multiple><el-button type="primary" link>{{ $t('excel.clickUpload') }}</el-button></el-upload></div>
</template><script setup lang="ts" name="upload-file">
import {useMessage} from '/@/hooks/message';
import {Session} from '/@/utils/storage';
import other from '/@/utils/other';
import {useI18n} from 'vue-i18n';const props = defineProps({modelValue: [String, Array],// 数量限制limit: {type: Number,default: 5,},// 大小限制(MB)fileSize: {type: Number,default: 5,},fileType: {type: Array,default: () => ['png', 'jpg', 'jpeg', 'doc', 'xls', 'ppt', 'txt', 'pdf', 'docx', 'xlsx', 'pptx'],},// 是否显示提示isShowTip: {type: Boolean,default: true,},uploadFileUrl: {type: String,default: '/admin/sys-file/upload',},type: {type: String,default: 'default',validator: (value: string) => {return ['default', 'simple'].includes(value);},},data: {type: Object,default:{}},dir: {type: String,default: ''},autoUpload: {type: Boolean,default: true,},
});const emit = defineEmits(['update:modelValue', 'change']);const number = ref(0);
const fileList = ref([]) as any;
const uploadList = ref([]) as any;
const fileUpload = ref();
const { t } = useI18n();// 请求头处理
const headers = computed(() => {return {Authorization: 'Bearer ' + Session.get('token'),'TENANT-ID': Session.getTenant(),};
});// 请求参数处理
const formData = computed(() => {return Object.assign(props.data,{dir: props.dir});
});// 上传前校检格式和大小
const handleBeforeUpload = (file: File) => {// 校检文件类型if (props.fileType.length) {const fileName = file.name.split('.');const fileExt = fileName[fileName.length - 1];const isTypeOk = props.fileType.indexOf(fileExt) >= 0;if (!isTypeOk) {useMessage().error(`${t('excel.typeErrorText')} ${props.fileType.join('/')}!`);return false;}}// 校检文件大小if (props.fileSize) {const isLt = file.size / 1024 / 1024 < props.fileSize;if (!isLt) {useMessage().error(`${t('excel.sizeErrorText')} ${props.fileSize} MB!`);return false;}}number.value++;return true;
};// 上传成功回调
function handleUploadSuccess(res: any, file: any) {if (res.code === 0) {uploadList.value.push({ name: file.name, url: res.data.url });uploadedSuccessfully();} else {number.value--;useMessage().error(res.msg);fileUpload.value.handleRemove(file);uploadedSuccessfully();}
}// 上传结束处理
const uploadedSuccessfully = () => {if (number.value > 0 && uploadList.value.length === number.value) {fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);uploadList.value = [];number.value = 0;emit('change', listToString(fileList.value));emit('update:modelValue', listToString(fileList.value));}
};const handleRemove = (file: any) => {fileList.value = fileList.value.filter((f) => !(f === file.url));emit('change', listToString(fileList.value));emit('update:modelValue', listToString(fileList.value));
};const handlePreview = (file: any) => {other.downBlobFile(file.url, {}, file.name);
};/*** 将对象数组转为字符串,以逗号分隔。* @param list 待转换的对象数组。* @param separator 分隔符,默认为逗号。* @returns {string} 返回转换后的字符串。*/
const listToString = (list: { url: string }[], separator = ','): string => {let strs = '';separator = separator || ',';for (let i in list) {if (list[i].url) {strs += list[i].url + separator;}}return strs !== '' ? strs.substr(0, strs.length - 1) : '';
};const handleUploadError = () => {useMessage().error('上传文件失败');
};/*** 监听 props 中的 modelValue 值变化,更新 fileList。*/
watch(() => props.modelValue,(val) => {if (val) {let temp = 1;// 首先将值转为数组const list = Array.isArray(val) ? val : props?.modelValue?.split(',');// 然后将数组转为对象数组fileList.value = list.map((item) => {if (typeof item === 'string') {item = { name: item, url: item };}item.uid = item.uid || new Date().getTime() + temp++;return item;});} else {fileList.value = [];return [];}},{ deep: true, immediate: true }
);const submit = () => {fileUpload.value.submit();
};defineExpose({submit,
});
</script>

2.分页组件

<template><el-pagination@size-change="sizeChangeHandle"@current-change="currentChangeHandle"class="mt15":pager-count="5":page-sizes="props.pageSizes":current-page="props.current"background:page-size="props.size":layout="props.layout":total="props.total"></el-pagination>
</template><script setup lang="ts" name="pagination">
const emit = defineEmits(['sizeChange', 'currentChange']);const props = defineProps({current: {type: Number,default: 1,},size: {type: Number,default: 10,},total: {type: Number,default: 0,},pageSizes: {type: Array as () => number[],default: () => {return [1, 10, 20, 50, 100, 200];},},layout: {type: String,default: 'total, sizes, prev, pager, next, jumper',},
});
// 分页改变
const sizeChangeHandle = (val: number) => {emit('sizeChange', val);
};
// 分页改变
const currentChangeHandle = (val: number) => {emit('currentChange', val);
};
</script>

http://www.lryc.cn/news/429985.html

相关文章:

  • Mysql (面试篇)
  • 【python】深入探讨python中的抽象类,创建、实现方法以及应用实战
  • 微前端传值
  • 《学会 SpringBoot · 依赖管理机制》
  • 全网行为管理软件有哪些?5款总有一款适合你的企业!
  • 以简单的例子从头开始建spring boot web多模块项目(二)-mybatis简单集成
  • Golang | Leetcode Golang题解之第354题俄罗斯套娃信封问题
  • jmeter中添加ip欺骗
  • WPF篇(19)-TabControl控件+TreeView树控件
  • appium下载及安装
  • XSS项目实战
  • SD-WAN降低网络运维难度的关键技术解析
  • 【算法基础实验】图论-最小生成树-Prim的即时实现
  • LLama 3 跨各种 GPU 类型的基准测试
  • FreeRTOS 快速入门(五)之信号量
  • centos 服务器之间实现免密登录
  • RabbitMq实现延迟队列功能
  • redis内存淘汰策略
  • 实时洞察应用健康:使用Spring Boot集成Prometheus和Grafana
  • 生信圆桌x生信豆芽菜:生物信息学新手的学习与成长平台
  • 创客匠人标杆对话(上):她如何通过“特长+赛道”实现财富升级
  • 最少钱学习并构建大模型ollama-llama3 8B
  • AVI视频损坏了怎么修复?轻松几步解决你的困扰
  • 【C++】map、set基本用法
  • 模型 闭环原理
  • 3007. 价值和小于等于 K 的最大数字(24.8.21)
  • 微服务 - 分布式锁的实现与处理策略
  • Catf1ag CTF Web(九)
  • QT QFileDialog 类
  • 了解 K-Means 聚类的工作原理(详细指南)