赞
踩
<template> <el-form :model="formData" :rules="formRules" ref="formRef" label-width="80px" class="child-form" > <!-- Your form fields go here --> <el-form-item label="Field 1" prop="field1"> <el-input v-model="formData.field1"></el-input> </el-form-item> <el-form-item label="Field 2" prop="field2"> <el-input v-model="formData.field2"></el-input> </el-form-item> </el-form> </template> <script lang="ts"> import { defineComponent, ref } from 'vue'; export default defineComponent({ name: 'ChildComponent', props: { componentName: String, }, setup(props) { const formData = ref({ field1: '', field2: '', }); const formRules = { field1: [{ required: true, message: 'Field 1 is required', trigger: 'blur' }], field2: [{ required: true, message: 'Field 2 is required', trigger: 'blur' }], }; const validateForm = () => { return new Promise((resolve) => { props.$refs.formRef.validate((valid) => { resolve(valid); }); }); }; return { formData, formRules, validateForm, }; }, }); </script> <style scoped> .child-form { margin-bottom: 20px; } </style>
<template> <div> <child-component v-for="(child, index) in childComponents" :key="index" :componentName="`Child ${index + 1}`" ref="childRefs" ></child-component> <el-button type="primary" @click="saveForm">保存</el-button> </div> </template> <script lang="ts"> import { defineComponent, ref } from 'vue'; import ChildComponent from '@/components/ChildComponent.vue'; // Adjust the path accordingly export default defineComponent({ name: 'ParentComponent', components: { ChildComponent, }, setup() { const childComponents = ref([1, 2, 3]); // Adjust the number of child components as needed const childRefs = ref([]); const saveForm = async () => { let validationPassed = true; for (const childRef of childRefs.value) { const valid = await childRef.validateForm(); if (!valid) { validationPassed = false; alert(`Validation failed for ${childRef.componentName}`); break; } } if (validationPassed) { // Perform your request here alert('All forms are valid. Proceed with the request.'); } }; return { childComponents, childRefs, saveForm, }; }, }); </script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。