使用场景:同页面中下tab栏切换多个form表单组件,只有一个提交按钮,各组件下的表单数据分别提交,tab栏的兄弟组件传值。
实现方式:
- 父组件通过两次调用$refs获取子组件的方法。
- 子组件内部getData方法返回表单数据,父调用子组件1的getData方法获取子组件1的表单数据并传给子组件2。
父组件:
<template> <div> <el-tabs v-model="activeName" type="card" @tab-click="handleClick"> <el-tab-pane label="form1" name="first"> <form-comp-one ref="formComp1" /> </el-tab-pane> <el-tab-pane label="form2" name="second"> <form-comp-two ref="formComp2" /> </el-tab-pane> </el-tabs> <el-button class="submit-btn" size="small" @click="submit">提交</el-button> </div> </template> <script> import FormCompOne from "@/components/FormCompOne.vue"; import FormCompTwo from "@/components/FormCompTwo.vue"; export default { components: { FormCompOne, FormCompTwo, }, data() { return { activeName: "first", }; }, methods: { // handleClick(tab, event) { // console.log(tab, event); // }, submit() { this.$refs.formComp1.submitForm(); const formData1 = this.$refs.formComp1.getData(); this.$refs.formComp2.submitForm(formData1.code); }, }, }; </script> <style> .submit-btn { position: absolute; right: 10px; top: 60px; } </style> 子组件1: <template> <el-form ref="formData" :model="formData" :rules="formRules" label-width="80px" style="width: 450px" > <el-form-item label="编号" prop="code"> <el-input class="f-input" v-model="formData.code"></el-input> </el-form-item> <el-form-item label="产品名称" prop="name"> <el-input class="f-input" v-model="formData.name"></el-input> </el-form-item> </el-form> </template> <script> class formData { constructor() { this.name = ""; this.code = ""; } static getRule() { return { name: [{ required: true, message: "请填写名称", trigger: "blur" }], code: [{ required: true, message: "请填写编号", trigger: "blur" }], }; } } export default { data() { return { formData: new formData(), formRules: formData.getRule(), }; }, methods: { getData() { // 返回子组件的form return this.formData; }, submitForm(){ // 表单数据提交 } }, }; </script> <style scoped> </style> 标签:vue,elementui,formData,表单,tab,组件,getData,refs From: https://www.cnblogs.com/yuro12138/p/17084219.html