先看效果
代码如下
父组件
<template>
<ChildForm ref="childFormRef" />
<button @click="validateForm">校验表单</button>
</template>
<script setup>
import { ref } from 'vue';
import ChildForm from './ChildForm.vue';
const childFormRef = ref(null);
const validateForm = async () => {
if (childFormRef.value) {
try {
const isValid = await childFormRef.value.validate();
console.log('Form valid:', isValid);
} catch (error) {
console.error('Validation error:', error);
}
}
};
</script>
子组件
<!-- ChildForm.vue -->
<template>
<van-form ref="formRef">
<!-- 表单项 -->
<van-field label="账号" name="账号" v-model="pageList.fieldValue" :rules="rules" />
<van-field
v-model="pageList.password"
label="密码"
name="密码"
type="password"
placeholder="请输入密码"
:rules="[{ required: true, message: '请输入密码' }]"
/>
</van-form>
</template>
<script setup>
import { ref, defineExpose } from 'vue';
const formRef = ref(null);
let pageList = ref({
fieldValue:'',
password:'',
})
const rules = ref([
{ required: true, message: 'This field is required' }
]);
const validate = async () => {
if (formRef.value) {
try {
await formRef.value.validate();
return true;
} catch (error) {
return false;
}
}
return false;
};
defineExpose({ validate });
</script>
父组件通过ref
获取子组件的引用,在父组件的点击事件中调用子组件的validate
方法进行表单验证,如果验证通过则执行提交逻辑。子组件通过defineExpose
暴露其validate
方法给父组件使用。这样父组件就可以通过childForm.value.validate
调用子组件的验证方法了。