赞
踩
<template> <el-form ref="form" :model="formData" :rules="formRules" 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> <!-- Add more form fields as needed --> </el-form> </template> <script lang="ts"> import { defineComponent, ref } from 'vue'; export default defineComponent({ name: 'ChildComponent', props: { componentName: String, // Add a prop to store the component name }, setup(props) { const formData = ref({ field1: '', field2: '', // Add more fields as needed }); const formRules = { field1: [{ required: true, message: 'Field 1 is required', trigger: 'blur' }], field2: [{ required: true, message: 'Field 2 is required', trigger: 'blur' }], // Add more rules as needed }; return { formData, formRules, }; }, }); </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}`" ></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 saveForm = () => { let validationPassed = true; for (const child of childComponents.value) { const childForm = child.$refs.form; // Access the form reference in the child component childForm.validate((valid) => { if (!valid) { validationPassed = false; alert(`Validation failed for ${child.componentName}`); } }); if (!validationPassed) { break; // Stop validation if any child form fails } } if (validationPassed) { // Perform your request here alert('All forms are valid. Proceed with the request.'); } }; return { childComponents, saveForm, }; }, }); </script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。