子组件
searchForm
<template><el-formref="form":model="value":rules="rules":label-width="labelWidth":inline="inline"><el-form-itemv-for="field in fields":key="field.slot":label="field.label":prop="field.slot"><slot :name="field.slot"><el-inputv-if="!$slots[field.slot]"v-model="formValue[field.slot]"@input="updateValue(field.slot, $event)"/></slot></el-form-item><el-buttontype="primary"@click="submitForm">搜索</el-button><el-button @click="resetForm">重置</el-button></el-form>
</template><script>
import {defineComponent, ref, watch,
} from 'vue';export default defineComponent({name: 'SearchForm',props: {value: {type: Object,default: () => ({}),},fields: {type: Array,default: () => [],},rules: {type: Object,default: () => ({}),},labelWidth: {type: String,default: '100px',},inline: {type: Boolean,default: true,},},setup(props, { emit }) {const form = ref(null);const formValue = ref({ ...props.value });watch(() => props.value, (newValue) => {formValue.value = { ...newValue };}, { deep: true });const submitForm = () => {form.value.validate((valid) => {if (valid) {emit('submit', props.value);} else {console.log('error submit!!');return false;}});};const resetForm = () => {form.value.resetFields();emit('reset');};const updateValue = (key, value) => {emit('input', {...formValue.value,[key]: value,});};return {form,formValue,submitForm,resetForm,updateValue,};},
});
</script>
<style scoped>
v-deep .el-button--primary{margin: 0;
}
</style>
父组件
html<p>父{{ searchFormModel }}</p><search-formref="searchFormRef"v-model="searchFormModel":fields="searchFromFields":rules="rules"@submit="onSearchFormSubmit"@reset="onSearchFormReset"><template #ruleId><el-selectv-model="searchFormModel.ruleId"placeholder="请选择活动区域"><el-optionlabel="区域一"value="shanghai"/><el-optionlabel="区域二"value="beijing"/></el-select></template><template #type><el-checkbox-group v-model="searchFormModel.type"><el-checkboxlabel="美食/餐厅线上活动"name="type"/><el-checkboxlabel="地推活动"name="type"/><el-checkboxlabel="线下主题活动"name="type"/><el-checkboxlabel="单纯品牌曝光"name="type"/></el-checkbox-group></template></search-form>// 引入import searchForm from './searchForm';// 注册components: {searchForm,},setup() {const initData = reactive({searchFormModel: {categoryIds: '666',ruleId: '',type: [],},searchFromFields: [{ label: '活动名称', slot: 'categoryIds' },{ label: '活动区域', slot: 'ruleId' },{ label: '活动性质', slot: 'type' },],rules: {categoryIds: [{ required: true, message: '请输入用户名', trigger: 'blur' },],ruleId: [{ required: true, message: '请选择活动区域', trigger: 'change' },],type: [{type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change',},],},searchFormRef: null,});const onSearchFormSubmit = (form) => {console.log('表单提交了', form);};const onSearchFormReset = () => {console.log('表单重置了');// initData.searchFormRef.resetFields();};