element ui dialog 表单点击编辑,再点击添加,数据无法清空问题 解决办法

798 阅读1分钟

image.png 看网上也存在很多这种问题

首先理解 Dialog 显示与隐藏

dialog.gif

image.png

源码中其实也是通过v-show控制的

image.png

第一次生成form 确定初始值

image.png 这个时候点击编辑 点击重置这个时候其实值 还是在的

刷新先打开新增

dialogedit.gif 这个时候 重置是空值

结论:

form表单的重置是以第一次打开的数据作为重置标准,如果先打开的是更新,那么重置之后以第一次更新的数据作为标准;  Dialog 中的内容是懒加载的,目前 edit (更新)方法的写法导致 Form 刚加载出来时值就已经是新的了,所以 resetFields 也只能回到新值  

解决方案:

1、利用v-if的特性,进行form的销毁和重建,强行让每一次改操作拿到的数据为父组件传过来的初始值

<el-dialog  :title="title"  
            :close-on-press-escape="false" 
            :close-on-click-modal="false" 
            :visible.sync="payfeeVisible" 
            v-if='payfeeVisible'
            width="430px">

2、让表单先渲染出来,再对表单对象进行赋值

if(type==1){//添加
     this.title = '添加';  
}else{//编辑
     //对form赋值   
     this.title = '编辑';
     this.$nextTick(() => {
         this.payfee.fee = row.price;
         this.rowid = row.id;
    })
}

3.只需要在close 加上重置表单就行

this.$refs[form].resetFields()

image.png

resetFields() 不好的点:

1.如果每次打开都需要重新渲染 调取大量的接口其实也不好

so 不用这个resetFields()方法处理也是可以的 改为clearValidate 需要在每次 close 清空值就行了 这种写法更推荐一点

edit 编辑的时候 也不需要nextTick赋值 直接赋值就好
 //手动清空表单的值 比如:
this.formData.id = '';
this.formData.username = '';
// 关键就是这句话!
this.$refs["formName"].clearValidate(); // 取消表单验证

2.resetFields 只对于绑定prop的值清空 比如里面有table 还需要结合手动清空 pageNum =1 pageSize = 10 处理起来感觉很乱

完整代码:

    <el-dialog title='新增窗口' v-if="dialogVisible" :visible.sync="dialogVisible" @open="openDialog"
      @close="closeDialog('ruleForm')">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px"
        class="demo-ruleForm">
        <el-form-item label="活动名称" prop="name">
          <el-input clearable v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="活动区域" prop="region">
          <el-select style="width:100%" clearable v-model="ruleForm.region" placeholder="请选择活动区域">
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    
    
     closeDialog(form) {
      this.$refs[form].resetFields()
      console.log("关闭了-----ruleForm", this.ruleForm);
    },
    edit() {
      this.dialogVisible = true
      //一定要再打开的后面
      this.$nextTick(() => {
        this.ruleForm.name = "lulu"
        this.ruleForm.region = "shanghai"
      });
    },
    see() {
      this.dialogVisible = true
    },