vue3组件封装系列-表单请求

news/2024/9/30 0:22:41/

我们在开发一些后台管理系统时,总是会写很多的列表查询页面,如果不封装组件,就会无限的复制粘贴,而且页面很冗余,正常情况下,我们都是要把组件进行二次封装,来达到我们想要效果。这里我分享一下我近期封装的关于列表的组件封装。
vue3+element-plus

表单组件

src\components\TableSeach

<template><div class="table-search-root"><el-formref="searchForm"class="table-search__form":model="formData"size="default"label-width="128px"v-bind="formProps"><!-- 查询表单模块 --><el-row class="table-search__row"><el-colv-for="(field, index) in fields":key="field.prop"class="table-search__col":class="{ 'form__item--hidden': shouldCollapse(index) }":xl="6":lg="8":md="12":sm="24"><el-form-item :label="field.label" :prop="field.prop"><slot v-if="$slots[field.prop]" :name="field.prop"></slot><componentv-else:is="field.type"v-model.trim="formData[field.prop]":placeholder="defaultPlaceHolder(field)"v-bind="getFormFieldProps(field.type, field.props)"><template v-if="field.type === FieldsType.SELECT"><el-optionv-for="option in field.options":key="option.value":label="option.label":value="option.value"/></template></component></el-form-item></el-col><!-- 操作按钮模块 --><div class="table-search__btns"><el-button type="primary" :loading="props.loading" @click="handleSearch">查询</el-button><el-button :loading="props.loading" @click="handleReset"> 重置 </el-button><spanv-if="showCollapseBtn"class="table-search__btn--filter ml-28"@click="toggleCollapse">{{ isCollapse ? '展开' : '收起' }}<el-icon color="#c0c4cc" v-show="isCollapse"><CaretBottom /></el-icon><el-icon color="#c0c4cc" v-show="!isCollapse"><CaretTop /></el-icon></span></div></el-row></el-form></div>
</template>
<script lang="ts">
// 解决组件不渲染问题---使用的是自动引入方式,不知为何有bug,暂时只能用这种方式解决,有好办法的也可以分享一下 
import {ElInput,ElInputNumber,ElSelect,ElTimePicker,ElTimeSelect,ElDatePicker
} from 'element-plus';
export default {components: {ElInput,ElInputNumber,ElSelect,ElTimePicker,ElDatePicker,ElTimeSelect}
};
</script>
<script setup lang="ts">
import { type PropType, ref, toRefs, computed } from 'vue';
import defaultFieldsProps from './defaultFieldsProps';
const FieldsType = {INPUT: 'el-input',SELECT: 'el-select'
};
type filed = {prop: string;label?: string;type?: string;options?: any[];[propName: string]: any;
};
interface size {width: number;quantity: number;
}
// 不同尺寸所对应的页面宽度和每行 ElFormItem 个数
const DifferentSizeData = [{ width: 1900, quantity: 4 }, // xl{ width: 1200, quantity: 3 }, // large{ width: 992, quantity: 2 }, // middle{ width: 768, quantity: 1 }, // small{ width: 0, quantity: 1 } // less than small
];
const props = defineProps({modelValue: {type: Object,default: () => ({})},formProps: {type: Object,default: () => ({})},fields: {type: Array as PropType<filed[]>,default: () => []},defaultCollapse: {type: Boolean,default: false},loading: {type: Boolean,default: false}
});
const formData: { [key: string]: any } = defineModel();
const emit = defineEmits(['search', 'reset']);
const { defaultCollapse, fields, formProps } = toRefs(props);
const isCollapse = ref(true);
isCollapse.value = defaultCollapse.value;
const searchForm = ref<any>(null);
const showCollapseBtn = computed(() => {const quantity = getPerLineItemQuantity();return fields.value.length >= quantity;
});
const getFormFieldProps = (fieldType: any, props: any) => {const defaultProps: { [key: string]: any } = defaultFieldsProps;return { ...defaultProps[fieldType], ...props };
};
const shouldCollapse = (index: any) => {const quantity = getPerLineItemQuantity();return index > quantity - 2 && isCollapse.value;
};
const getPerLineItemQuantity = () => {const documentScrollWidth = document.documentElement.scrollWidth;const size = DifferentSizeData.find((item) => documentScrollWidth >= item.width);return (size as size).quantity;
};
const defaultPlaceHolder = (field: any) => {const newLabel = field.label.replace(':', '').replace(':', '');return field.type === FieldsType.SELECT ? `请选择${newLabel}` : `请输入${newLabel}`;
};
const toggleCollapse = () => {isCollapse.value = !isCollapse.value;
};
const handleSearch = () => {emit('search', formData.value);
};
const handleReset = () => {searchForm.value.resetFields();emit('reset', formData.value);
};
const handleResetForm = () => {searchForm.value.resetFields();
};
defineExpose({handleResetForm
});
</script>
<style lang="scss" scoped>
/**  查询表单模块样式  **/
.table-search__form {display: flex;flex-wrap: wrap;
}.table-search__row {width: 100%;
}.table-search__col:last-of-type {margin-bottom: 0;
}:deep(.el-form-item__label) {width: 128px;white-space: nowrap;overflow: hidden;font-weight: 400;font-size: 14px;color: #282828;
}:deep(.el-select),
:deep(.el-cascader),
:deep(.el-date-editor--daterange.el-input),
:deep(.el-date-editor--daterange.el-input__inner),
:deep(.el-date-editor--timerange.el-input),
:deep(.el-date-editor--timerange.el-input__inner),
:deep(.el-date-editor--datetimerange.el-input),
:deep(.el-date-editor--datetimerange.el-input__inner) {width: 100%;
}:deep(.el-date-editor .el-range-separator) {width: auto;
}.form__item--hidden {display: none;
}/**  操作按钮模块样式  **/
.table-search__btns {margin-left: auto;margin-bottom: 16px;
}.table-search__btn--filter {font-size: 14px;color: #606266;cursor: pointer;
}/**  功能样式  **/
.ml-28 {margin-left: 28px;
}
</style>

src\components\TableSeach\defaultFieldsProps.ts

export default {'date-picker': {valueFormat: 'x',},XXXXX这里写一些项目公共的想要特殊处理的参数
};

表单组件就是这样

使用效果

收起状态
在这里插入图片描述

展开状态
在这里插入图片描述

使用方式

<template><TableSeachv-model="searchQuery"ref="TableSeach":fields="serchFields":formProps="{labelWidth: '120px'}":loading="loading.tableLoading"@search="handleQuery"@reset="handleQuery"><template #staff_ids>基础组件无法实现的情况下可以用插槽的方式添加其他组件用以实现</template><template #tags>基础组件无法实现的情况下可以用插槽的方式添加其他组件用以实现</template></TableSeach>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import TableSeach from '@/components/TableSeach/index.vue';const searchQuery = ref({xxxxxxx:xxxxx
});
const loading = ref({tableLoading: false
});onMounted(() => {handleQuery();
});
const handleQuery = async () => {xxxxxxxxxxx
};const serchFields = [{label: 'xxxxxx',prop: 'time',type: FormType.DATE_PICKER,props: {type: 'daterange',startPlaceholder: '开始日期',endPlaceholder: '结束日期',disabledDate: disabledDate, valueFormat: YMD}},{label: 'xxxxxxx',prop: 'staff_ids'},{label: 'xxxxx',prop: 'tags'},{label: 'xxxxxx',prop: 'loss',type: FormType.SELECT,options: [{ value: -1, label: '全部' }, ...dynamicList]},{label: 'xxxxxx',prop: 'del_staff_id',type: FormType.SELECT,options: staffOptions.value,props: {filterable: true,remote: true,loading: loading.value.staffLoading,remoteMethod: remoteStaffMethod}},xxxxxxxxxxxxxxxx
]
</script>

如上,除了部分参数key是需要固定以外,其余element本身自带的参数也全部可以使用props传入,特殊需求在组件不满足情况下也可以使用插槽形式更改显示

本示例只是简单写了一下,在某些情况下需要传入参数也可以将serchFields改为function接收参数

有什么问题的欢迎提出,也欢迎大佬指出不足之处


http://www.ppmy.cn/news/1431162.html

相关文章

【链表】Leetcode 两数相加

题目讲解 2. 两数相加 算法讲解 我们这里设置一个头结点&#xff0c;然后遍历两个链表&#xff0c;使用一个flag记录相加的结果和进位&#xff0c;如果两个链表没有走到最后或者进位不等于0&#xff0c;我们就继续遍历处理进位&#xff1b;如果当前的链表都遍历完成了&#x…

asio之地址

address address作为address_v4和address_v6的包装器 #mermaid-svg-XZWMK64K5NucyHdI {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-XZWMK64K5NucyHdI .error-icon{fill:#552222;}#mermaid-svg-XZWMK64K5NucyHdI …

《前端面试题》- TypeScript - TypeScript的优/缺点

问题 简述TypeScript的优/缺点 答案 优点 增强了代码的可读性和可维护性包容性&#xff0c;js可以直接改成ts&#xff0c;ts编译报错也可以生成js文件&#xff0c;兼容第三方库&#xff0c;即使不是ts编写的社区活跃&#xff0c;完全支持es6 缺点 增加学习成本增加开发成…

Tesseract OCR 的使用

目录 前言一、简介二、下载与安装2.1 下载2.2 安装2.3 配置环境变量 三、基本使用四、Java 整合4.1 导入依赖4.2 添加语言库4.3 代码示例 五、训练字库5.1 为什么要训练字库5.2 jTessBoxEditor 前言 如果想要通过代码的方式去识别图片中的文字&#xff0c;通常有以下几种方法&…

OpenCV-复数矩阵点乘ComplexMatrixDotMultiplication

作者&#xff1a;翟天保Steven 版权声明&#xff1a;著作权归作者所有&#xff0c;商业转载请联系作者获得授权&#xff0c;非商业转载请注明出处 需求说明 一般用到FFT&#xff0c;就涉及到复数的计算&#xff0c;为了便于调用&#xff0c;我自行封装了一个简单的复数矩阵点乘…

JVM中的堆和栈

在Java虚拟机(JVM)中&#xff0c;堆(heap)和栈(stack)是两个重要的内存区域&#xff0c;分别用来存储不同类型的数据。 堆是用来存储对象的内存区域&#xff0c;所有的Java对象都在堆中分配内存。堆是一个动态的内存区域&#xff0c;它的大小可以在程序运行时动态调整。Java垃…

大舍传媒国外活动策划,助您在国际舞台上大放异彩

一、引言 随着全球化的不断深入&#xff0c;越来越多的企业开始将目光投向国际市场。为了更好地拓展业务&#xff0c;提升企业品牌的国际影响力&#xff0c;各种海外活动策划和海外演议一站式服务需求日益增加。大舍传媒凭借多年的行业经验和专业团队&#xff0c;为您提供全方…

第52篇:算法的硬件实现<三>

Q&#xff1a;本期我们介绍二进制搜索算法电路&#xff0c;用于查找某个数据在数组中的位置。 A&#xff1a;基本原理&#xff1a;从数组的中间元素开始&#xff0c;如果给定值和中间元素的关键字相等&#xff0c;则查找成功&#xff1b;如果给定值大于或者小于中间元素的关键…