表单代码
<el-form :label-width="120" :rules="formRules" :model="form" ref="form"> <el-form-item label="活动名称" prop="name"> <el-input v-model="form.name"></el-input> </el-form-item> </el-form> <el-button type="info" @click="save">保存</el-button> <el-button type="info" @click="empty">重置</el-button>方法
// 校验规则 formRules: { name: [ { required: true, message: '请输入活动名称', trigger: 'blur' }, { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' } ], } /** * 保存函数 */ save() { this.$refs['form'].validate((valid) => { if (valid) { alert('submit!'); } else { console.log('error submit!!'); return false; } }); } //有可能this.$refs['form'].validate() 方式不识别。需要使用: this.$refs.form.validate(); }) empty() { //重置 //根据需求二选一 /** * 移除校验结果并重置字段值 * 注:清除表单项name的校验及数值 */ this.$refs.form.resetFields(); /** * 移除校验结果 * 注:只清除表单项name的校验,不清楚表单项name的数值 */ this.$refs.form.clearValidate('name'); })表单方法(Element官网说明):
方法名说明参数validate对整个表单进行校验的方法,参数为一个回调函数。该回调函数会在校验结束后被调用,并传入两个参数:是否校验成功和未通过校验的字段。若不传入回调函数,则会返回一个 promiseFunction(callback: Function(boolean, object))validateField对部分表单字段进行校验的方法Function(prop: string, callback: Function(errorMessage: string))resetFields对整个表单进行重置,将所有字段值重置为初始值并移除校验结果—clearValidate移除表单项的校验结果。传入待移除的表单项的 prop 属性组成的数组,如不传则移除整个表单的校验结果Function(props: array)注: clearValidate方法使用,注意element ui的版本:element ui^2.4.3才支持传入参数,清空指定校验结果的 FormItem
按版本安装可以看我的另一篇文章:npm 安装指定版本(按版本安装)
相关文章: Form 表单(Element官网) https://www.cnblogs.com/weiqinl/p/6708993.html
