vue + element 表单清空及验证

553 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第6天,点击查看活动详情

问题:

  1. element表单提交后不仅要清空表单内容,还要清空验证报错信息 但是直接 this.$refs.ruleFormName.clearValidate() 经常不起作用

  2. 需要验证一个输入框,但是它是非必填,不能prop后在rules里直接验证,可是要有提示且必须在当前输入框底下,和正常必填字段一样的显示方式

解决方案: 可以定义一个清空表单的方法,当执行某些操作后,调用此方法。 eg:

clearForm() {
            setTimeout(() => {
                    this.ruleForm = {
                            name: '',
                            logo: '',
                            address: '',
                            kpi: ''
                    }
             this.$refs.ruleForm && this.$refs.ruleForm.clearValidate && this.$refs.ruleForm.clearValidate()
	}, 200)
},

清空方法其实this.$refs.ruleForm && this.$refs.ruleForm.clearValidate()就可以了 也可以用最新语法this.$refs?.ruleForm?.clearValidate()

定义变量errorMsg,输入框上绑定error属性

	<el-form-item label="问题根源:" :error="errorMsg">
                <el-input
                    :disabled="ruleForm.issueType == 1"
                    v-model="ruleForm.issueCauses"
                    @blur="formatIssueCauses(ruleForm.issueCauses)"
                    placeholder="请输入问题根源"
                ></el-input>
        </el-form-item>

失去焦点时验证该输入框:

	formatIssueCauses(val) {
            if (val.length > 50) {
                this.errorMsg = Math.random()
                this.$nextTick(() => {
                        this.errorMsg = '问题措施不能超过50个字符'
                })
            }
        },

this.errorMsg = Math.random()为了解决error属性的提示信息只会在首次奏效问题。