需求描述
在表单中,可能部分表单项需封装成自定义组件,如何在表单提交时,能同步触发自定义组件的表单校验?
解决方案
将表单绑定的变量传入自定义组件中,在自定义组件中定义表单校验规则
完整代码范例
表单
内嵌自定义组件
src\test\index.vue
<template> <div style="padding: 30px; width: 300px"> <el-form ref="formRef" :model="searchData" label-width="80px" size="mini"> <el-form-item label="姓名" prop="name" :rules="{ required: true, message: '不能为空' }" > <el-input v-model="searchData.name"></el-input> </el-form-item> <SearchJob :searchData="searchData" /> <el-form-item> <el-button type="primary" @click="search">搜索</el-button> <el-button type="primary" @click="reset">重置</el-button> </el-form-item> </el-form> </div> </template> <script> import SearchJob from "./search_job.vue"; export default { components: { SearchJob, }, data() { return { searchData: {}, }; }, mounted() {}, methods: { search() { this.$refs.formRef.validate((valid) => { if (valid) { alert("通过表单校验,开始搜索!"); } }); }, reset() { this.searchData = {}; }, }, }; </script>
内嵌组件
src\test\search_job.vue
<template> <el-form-item label="工作" prop="job" :rules="{ required: true, message: '不能为空' }" > <el-input v-model="searchData.job"></el-input> </el-form-item> </template> <script> export default { props: { searchData: Object, }, }; </script>