vue3+ts封装el-select el-input通用组件

你还在为项目中多个页面输入框下拉框样式不统一而苦恼吗,你还在为页面中书写大段重复代码而痛苦吗?那就使用这个组件吧!此组件将输入框和下拉框统一封装,一行代码到处复用!
最近为了统一项目样式,决定将列表头部的输入框和下拉框统一封装,这样无论是哪个页面的输入下拉都看起来一样啦,代码如下:

<template>
  <div class="component_wapper">
    <el-row :gutter="16">
      <el-col v-for="(item, index) in props.searchFormDesc" :key="index" :span="item.layout || 6">
        <slot :name="`search-${item.searchKey}`" :form-data="searchFormData">
          <component
            :is="item.searchType === 1 ? ElInput : ElSelect"
            v-model="searchFormData[item.searchKey]"
            :placeholder="item.placeholder"
            clearable
            :disabled="item.disabled"
            :prefix-icon="item.searchType === 1 ? Search : ''"
            @change="formDataChange"
          >
            <template v-if="item.searchType === 2 && item.option" #default>
              <el-option
                v-for="op in item.option"
                :key="op[item.optionLabel || 'label']"
                :value="op[item.optionValue || 'value']"
                :label="op[item.optionLabel || 'label']"
              />
            </template>
          </component>
        </slot>
      </el-col>
    </el-row>
  </div>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';

  import { Search } from '@element-plus/icons-vue';

  import { searchFormDescType } from './index';
  import { ElInput, ElSelect } from 'element-plus';
  const props = defineProps<{
    searchFormDesc: Array<searchFormDescType>;
  }>();
  const emits = defineEmits(['submit']);
  //搜索词表单
  const searchFormData = ref({});
  const formDataChange = () => {
    emits('submit', searchFormData.value);
  };
</script>
<style scoped lang="scss">
  .component_wapper {
    width: 100%;
    :deep(.el-row) {
      width: 100%;
    }
  }
</style>

ts如下:

export interface searchFormDescType {
  searchKey: string; //搜索关键字
  searchType: number; //类型:1输入框,2下拉框 
  placeholder?: string;   
  option?: Array<{
      //下拉框通常默认接收为label,value,但是又特殊情况,在此自行传入
    [key: string]: string | number | boolean;
  }>;
  //组件占比
  layout?: string;
  disabled?: boolean;
 // 自定义下拉框label
  optionLabel?: string;
  // 自定义下拉框value
  optionValue?: string;
}

使用方式
在这里插入图片描述

在这里插入图片描述

注释:
vue3中使用component标签不能直接使用 is=“el-input”,要先引入element-plus中的组件,然后通过判断进行使用 :is=“item.searchType === 1 ? ElInput : ElSelect”
结果:

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿乐今天敲代码没

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值