首先我们还是看一下文章:https://blog.csdn.net/weixin_37930716/article/details/90234705 的内容
笔者在参考该文章的时候,踩了一个坑,是vue父子组件通信中使用ref传参的问题!
该文章的作者的弹框组件是和父组件写在同一个vue文件里的,也就是没有单独把弹框的页面代码写在另一个vue文件里。这样在父子组件通信的时候其实只有两级通信,如果写在单独的一个vue文件里,实际上就是三级通信。
清除上一次验证结果的代码就应该是:
if (this.$refs.子组件名称.$refs.editForm)
this.$refs.子组件名称.$refs.editForm.resetFields();
<template>
<basic-container>
<el-row>
<el-col :span="22"></el-col
><el-col :span="2"
><el-button type="primary" round @click="handleAddDialogOpen"
>添加</el-button
></el-col
>
</el-row>
<el-dialog
title="测试对话框"
top="200px"
width="40%"
:fullscreen="false"
:visible.sync="visible"
:close-on-click-modal="true"
>
<el-row
><el-form :model="test" ref="refdata"
><el-form-item
label="测试输入框"
prop="testinput"
:rules="[{ required: true, message: '不能为空' }]"
><el-input v-model="test.testinput"></el-input></el-form-item
></el-form>
</el-row>
</el-dialog>
</basic-container>
</template>
此时只有两级通信,在【添加】按钮点击事件中添加如下代码即可:
handleAddDialogOpen() {
if (this.$refs.refdata) {
this.$refs.refdata.clearValidate();
}
this.visible = true;
},
【添加】按钮所在的 父组件的代码(简单示意)
<template>
<basic-container>
<el-row>
<el-col :span="22"></el-col
><el-col :span="2"
><el-button type="primary" round @click="handleAddDialogOpen"
>添加</el-button
></el-col
>
</el-row>
<testDialog ref="testDlg"> </testDialog>
</basic-container>
</template>
<script>
import testDialog from "./testDialog";
export default {
components: { testDialog }
data() {
return {
... //此处省略
}
},
methods: {
handleAddDialogOpen(row) {
...//此处省略
}
}
}
</script>
testDialog 对话框子组件的另一个vue文件的代码:(注意ref参数)
<template>
<basic-container>
<el-dialog
title="测试对话框"
top="200px"
width="40%"
:fullscreen="false"
:visible.sync="visible"
:close-on-click-modal="true"
>
<el-row
><el-form :model="test" ref="testForm"
><el-form-item
label="测试输入框"
prop="testinput"
:rules="[{ required: true, message: '不能为空' }]"
><el-input v-model="test.testinput"></el-input></el-form-item
></el-form>
</el-row>
</el-dialog>
</basic-container>
</template>
此时,是三级组件的通信,注意看ref参数的定义。也就是说,对于【添加】按钮所在的父组件来说,testDlg是它的儿子,testForm是它的孙子。
如果要实现testForm里面的输入框的表单验证条件结果的清除,【添加】按钮的事件中的代码应该这样写:
handleAddDialogOpen() {
if (this.$refs.testDlg.$refs.testForm) {
this.$refs.testDlg.$refs.testForm.clearValidate();
}
this.visible = true;
},
笔者正是犯了这个错误,没有意识到是三级通信,还是按照那篇博客那样的写法,导致清除不掉。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有