美文网首页
Vue重置表单:TypeError: Cannot read p

Vue重置表单:TypeError: Cannot read p

作者: 流泪手心_521 | 来源:发表于2021-02-19 13:48 被阅读0次

    场景
    在对话框关闭或者取消时要重置表单,而Vue编译不通过,网上说是因为form表单未渲染进DOM,导致找不到此表单对象,导致:
    "TypeError: Cannot read property 'resetFields' of undefined"
    网友提供的解决办法:
    如果是第一次非空验证一下:

    if (this.$refs['dictForm'] !== undefined) {
                  this.closeDialog();//封装了清空操作
              }
    

    或者利用Vue的自带特性(DOM渲染后执行):

    this.$nextTick(()=>{    
            this.$refs.addForm.resetFields(); 
    })
    

    本次解决
    试过上述方案后还是没用,那么大概率是代码设计有问题了。
    官方提供了一个close的函数(摘自官网):

    before-close 仅当用户通过点击关闭图标或遮罩关闭 Dialog 时起效。如果你在 footer 具名 slot 里添加了用于关闭 Dialog 的按钮,那么可以在按钮的点击回调函数里加入 before-close 的相关逻辑。
    由于我理解错误,将close函数与before-close属性混用,导致Vue编译不通过,下边直接贴上代码:
    Vue代码:

    <el-dialog
            :title="title"
            :close-on-click-modal="false"//防止误点退出
            :visible.sync="centerDialogVisible"//控制是否显示
            @close="closeDialog"//对话框右上角自带的关闭按钮事件
            width="30%"
            center
            >
    

    Js代码:

                // 关闭新增/修改版块对话框
                closeDialog() {
                    this.dialogVisible=false
                    this.sectionColumnsCheckedList=[] //清空tree数据,也要清空 this.$refs.tree.setCheckedKeys([]);
                    if (this.$refs['dialogForm'] !== undefined) {
                        this.$refs['dialogForm'].resetFields();
                        this.$refs.tree.setCheckedKeys([]) //也要清空 this.$refs.tree.setCheckedKeys([]);
                    }else{
                        this.$nextTick(()=>{
                            this.$refs['dialogForm'].resetFields();
                            this.$refs.tree.setCheckedKeys([]) // 也要清空 this.$refs.tree.setCheckedKeys([]);
                        });
                    }
                }
    

    相关文章

      网友评论

          本文标题:Vue重置表单:TypeError: Cannot read p

          本文链接:https://www.haomeiwen.com/subject/chraxltx.html