element-ui的表单重置方法resetFields()无效问题

677 阅读1分钟

Element-ui的form表单验证清除问题一直是个坑,每次点开新增弹框或是打开编辑弹框时,表单的验证都没有正确地被清除。 单独用this.$refs['form'].clearValidate()好像不太行,于是就加上了nextTick,

this.$nextTick(() => {
  this.$refs['form'].clearValidate()
})

嗯,好像是没什么问题了,每次点开新增弹框,表单验证都有被好好地清除,可没想到,点完编辑再点新增,问题又来了,表单验证又出来了了。。。网上看了好久,终于找到一个比较靠谱的方法:
在打开新增弹框的时候加上

this['form'] = {}  // 需要多加这一步
this.$nextTick(() => {
  this.$refs['form'].resetFields() // 我这里是清空表单,包括数据
})
this.dialogVisible = true

在打开编辑弹框的时候加上

this.$nextTick(() => {
  this.$refs['form'].clearValidate() // 这里只是清空验证,没有清除数据
})
this.dialogVisible = false

记录一下这次的踩坑,不知道还有没有其他的解决方案。下面是部分代码:

<el-button type="primary" @click="handleAdd">新增</el-button>
<el-button size="mini" type="primary" @click="handleEdit">
  <span class="el-icon-edit"></span>编辑
</el-button>
<el-dialog
  title="系统维护管理"
  :visible.sync="dialogVisible"
  :close-on-click-modal="false"
  width="45%"
>
  <el-form ref="form" :model="form" :rules="rules" label-width="150px">
    <el-form-item label="记录编号:" prop="id">
      <el-input v-model="form.id" size="small" clearable></el-input>
    </el-form-item>
    <el-form-item label="名称:" prop="name">
      <el-input v-model="form.name" size="small" clearable></el-input>
    </el-form-item>
    <el-form-item label="链接地址:" prop="url">
      <el-input v-model="form.url" size="small" clearable></el-input>
    </el-form-item>
  </el-form>
  <div class="dialog_footer">
    <el-button size="small" @click="handleCancel">取 消</el-button>
    <el-button size="small" type="primary" @click="handleConfirm('form')">确 定</el-button>
  </div>
</el-dialog>
handleCancel () {
  this.$nextTick(() => {
    this.$refs['form'].clearValidate()
  })
  this.dialogVisible = false
},
handleEdit (row) {
  this.$nextTick(() => {
    this.$refs['form'].clearValidate()
  })
  this.dialogVisible = true
},
handleAdd () {
  this['form'] = {}
  this.$nextTick(() => {
    this.$refs['form'].resetFields()
  })
  this.dialogVisible = true
}