1、封装的search组件
<template>
<a-card>
<a-form
ref="formRef"
name="advanced_search"
:model="searchInfo"
:label-col="labelCol"
:wrapper-col="wrapperCol"
layout="inline"
>
<div v-for="(item, index) in searchData" :key="index">
<a-form-item v-if="item.type == 'input'" :label="item.label">
<a-input v-model:value="searchInfo[item.value]" :placeholder="item.placeholder" />
</a-form-item>
<a-form-item v-if="item.type == 'select'" :label="item.label">
<a-select
v-model:value="searchInfo[item.value]"
:placeholder="item.placeholder"
:options="item.menu"
style="width: 120px"
>
</a-select>
</a-form-item>
<a-form-item v-if="item.type === 'picker'" :label="item.label">
<a-date-picker
v-model:value="searchInfo[item.value]"
show-time
type="date"
:placeholder="item.placeholder"
style="width: 100%"
/>
</a-form-item>
</div>
<a-form-item :wrapper-col="{ span: 14, offset: 4 }">
<a-button type="primary" @click="onSubmit">搜索</a-button>
</a-form-item>
<a-form-item>
<a-button style="margin-left: 10px" @click="() => formRef.resetFields()>重置</a-button>
</a-form-item>
</a-form>
</a-card>
</template>
<script lang="ts">
import { Moment } from "moment";
import { defineComponent, reactive, toRaw } from "vue";
import type { FormInstance } from 'ant-design-vue';
export default defineComponent({
name: "search",
props: {
searchInfo: {
default: {},
type: Object,
},
searchData: {
default: [],
type: Array,
},
},
setup(props: any, ctx) {
// 决定着重置
const formRef = ref<FormInstance>();
const searchInfo: any = reactive(props.searchInfo);
const searchData = reactive(props.searchData);
const onSubmit = () => {
console.log("submit!", toRaw(searchInfo));
ctx.emit("submit-data", toRaw(searchInfo));
};
return {
labelCol: { span: 8 },
wrapperCol: { span: 16 },
formRef,
searchInfo,
onSubmit,
searchData,
};
},
});
</script>
2、使用组件
<template>
<div>
<Search
:searchData="searchData"
@submitData="submit"
:searchInfo="info"
></Search>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRaw } from "vue";
import Search from "@/components/search.vue";
export default defineComponent({
name: "Home",
components: {
Search,
},
setup() {
const searchArr = reactive([
{
type: "input",
value: "name",
label: "姓名",
placeholder: "请输入姓名",
},
{
type: "select",
value: "sex",
label: "性别",
placeholder: "请输入性别",
menu: [
{
value: 1,
label: "女",
},
{ value: 0, label: "男" },
],
},
{
type: "picker",
value: "date",
label: "日期",
},
]);
const searchInfo = reactive({
name: "",
sex: "",
date: "",
});
const submit = (value: object) => {
console.log(value, "我是组件返回的查询条件");
};
const searchData = toRaw(searchArr);
const info = toRaw(searchInfo);
return {
searchData,
submit,
info,
};
},
});
</script>