马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
先看结果
代码如下
父组件
- <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调用子组件的验证方法了。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |