Bug解决:ElementUI提交表单返回成功后自动清空表单的值

本文介绍了在Vue.js中如何清空ElementUI的form表单数据。当新增或编辑操作完成后,通常需要将表单重置以备下一次使用。文章提供了两种方法,一种是手动清除每个表单项,另一种是利用ElementUI的resetFields方法,该方法能够方便地清空所有使用prop属性绑定的表单数据。在实际开发中,特别是在表单项较多的情况下,推荐使用resetFields以提高效率。

在实际开发中,新增弹窗的form表单中输入内容后,新增成功后应该把form表单清空,不然下次再进入新增弹窗时,会有上次新增完的内容

方法一:form表单项少的话可以选择手动删除:

this.loginForm = {
                name:'',
                username:'',
                password:'',
                confirm: '',
                department: '',
                phone: ''
              }

方法二:以上的方法当然也是可以的,但是如果form表单有很多项的话,你需要写很多清空代码;
elementui中的form提供resetFields方法,用于清空所有表单数据,前提是表单项中要使用prop属性,绑定input中的v-model所绑定的字段,才可以被清空:

this.$nextTick(() => {
                if(this.$refs.loginForm){
                  //this.$refs.addForm.clearValidate();
                  this.$refs.loginForm.resetFields();//个人喜爱。clearValidate有时候验证清不掉,具体原因暂时没找到
                } 
            })

这样所有使用了prop属性的表单项都会被清空

注册功能方法的代码如下:

 register(){
         if (this.loginForm.password !== this.loginForm.confirm) {
        this.$message({
          type: "error",
          message: '2次密码输入不一致!'
        })
        return
      }

      this.$refs['loginForm'].validate((valid) => {
        if (valid) {
          request.post("/user/register", this.loginForm).then(res => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "注册成功"
              })
              // this.loginForm = {
              //   name:'',
              //   username:'',
              //   password:'',
              //   confirm: '',
              //   department: '',
              //   phone: ''
              // }
              this.$nextTick(() => {
                if(this.$refs.loginForm){
                  //this.$refs.addForm.clearValidate();
                  this.$refs.loginForm.resetFields();//个人喜爱。clearValidate有时候验证清不掉,具体原因暂时没找到
                } 
            })
              this.dialogVisible = false//注册成功后关闭注册弹窗,记得使用this.方法,不然关闭不了
              // this.resetForm(formName)
              // this.$refs[this.loginForm].resetFields()
              // this.$router.push("/modify")
            } else {
              this.$message({
                type: "error",
                message: res.message
              })
            }
          })
        }
      })
    },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值