Vue3——基于tdesign封装一个通用的查询组件

发布时间 2023-05-24 14:27:32作者: 。思索

前言

基于Vue3+TS+tdesign封装一个通用的查询组件;

临时写的一个demo

内容

组件代码

<template>
  <t-form ref="form" :model="formData" inline>
    <t-form-item v-for="item in formConfig" :key="item.name" :label="item.label">
      <component :is="item.type" v-model="formData[item.name]" :options="item.options"> </component>
    </t-form-item>
    <t-form-item>
      <t-space size="small">
        <t-button theme="primary" @click="submitForm">提交</t-button>
        <t-button theme="default" variant="base" @click="resetForm">重置</t-button>
      </t-space>
    </t-form-item>
  </t-form>
</template>
<script setup lang="ts">
import { defineProps, ref } from 'vue';

interface Props {
  formConfig: Array<{
    type: string;
    label: string;
    name: string;
    options?: any[];
  }>;
}

defineProps<Props>();

const emit = defineEmits(['submit']);

const formData = ref({});
const form = ref(null);

const submitForm = () => {
  emit('submit', formData);
};

const resetForm = () => {
  formData.value = {};
  emit('submit', formData);
};
</script>

使用

<template>
  <search-form :form-config="formConfig" @submit="onSubmit"></search-form>
</template>
<script setup lang="ts">
import searchForm from '@/components/form/search/index.vue';

const formConfig = [
  {
    type: 't-input',
    label: 'Name',
    name: 'name',
  },
  {
    type: 't-select',
    label: 'Gender',
    name: 'gender',
    options: [
      { label: 'Male', value: 'male' },
      { label: 'Female', value: 'female' },
    ],
  },
];

const onSubmit = (formData) => {
  console.log('父组件', formData.value);
};
</script>