1.插槽方式
//子组件
<el-form-item :class="isCustom?'custom-form-item':''"><div v-for="(item,index) in btnList" :key="index"><slot :item="item" :formRef="formRef"><FormButton:formData="modelForm":editable="editable":data="item"@onClick="onClick(item)"></FormButton></slot></div></el-form-item><script>
function onClick(data) {console.log(data.onClick,"data.onClick");if (!data.onClick) return;emit(data.onClick, props.modelForm.value);
}// 表单校验
async function validate() {if (!formRef.value) return;const result = await formRef.value.validate();return result;
}// 清除表单验证
async function resetFields() {if (!formRef.value) return await formRef.value.resetFields();return await formRef.value.resetFields();
}
</script>
父组件
<com-form :data="userSearchConfig.formItems" :modelForm="searchForm":btnList="userSearchConfig.buttons"><template v-slot:default="{item, formRef}"><el-button :type="item.type" @click="item.onClick(formRef)">{{item.name}}</el-button></template></com-form><script>
const btnList = userSearchConfig.value.buttons ? userSearchConfig.value.buttons : {};
// 查询用户
const onSubmit = async (formRef) => {if (!formRef) return;await formRef.validate((valid, fields) => {if (valid) {getUserData(searchForm);}});
};
// 重置表单
const onReset = (formRef) => {formRef.resetFields();
};
btnList.forEach(item=>{if(item.onClick === 'onSubmit'){item.onClick = onSubmit}if(item.onClick === 'onReset'){item.onClick = onReset}
})
</script>
2.$emit方式:
<FormButton:formData="modelForm":editable="editable":data="item"@onClick="onClick(item)"></FormButton>
<com-form ref="formRef" :data="userSearchConfig.formItems" :modelForm="searchForm":btnList="userSearchConfig.buttons" @onReset="onReset(formRef)" @onSubmit="onSubmit(formRef)"></com-form><script>
// 查询用户
const formRef = ref();const onSubmit = async () => {formRef.value.validate();let valid = formRef.value.validate();if(valid) await getUserData(searchForm);
};
// 重置表单
const onReset = () => {formRef.value.resetFields();
};
btnList.forEach(item=>{if(item.onClick === 'onSubmit'){item.onClick = onSubmit}if(item.onClick === 'onReset'){item.onClick = onReset}
})
</script>