ElementUI 表单验证

<el-form 
	:rules="rules" 
	:ref="formName" 
	:model="detail" 
	label-position="center" 
	label-width="90px">
</el-form>	
export default {
	data () {
		return {
			formName: "dataForm",
			titleText: '添加',
			visible: this.propVisible,
			detail: this.propDetail,
			detailId: this.propDetailId,
			rules: {
				LicensePlate1: [{ required: true, message: '请录入车牌号'}],                    
			},
		};
	},
	props: {
		propVisible: {
			type: Boolean,
			default: false
		},
		propFormType: {
			type: Number,
			default: 1,
		},
		propDetailId: {
			type: Number,
			default: -1,
		},
		propDetail: {
			type: Object,
			default: function(){ 
				return {
					CarID: -1,
					LicensePlate1: '',
					LicensePlate2: '',
					Brand: '',
					Series: '',
				}
			},
		}
	},
	updated() {
		this.clearValidate();  
	},
	methods: {
		handleBeforeClose() {   
			// 刷新当前页
			//location.reload();    
			this.handleCancel();
		},
		handleCancel(){        
			this.clearValidate();
			this.visible = false;
		},
		resetData: function() {
			this.clearValidate();         
		},
		clearValidate: function() {
			if (this.$refs[this.formName]) {
				this.$refs[this.formName].clearValidate();              
			}
		},
		resetFields: function() {
			if (this.$refs[this.formName]) {
				this.$refs[this.formName].resetFields();          
			}
		},
		copyData(obj){
			const jsonData = JSON.stringify(obj);
			return JSON.parse(jsonData); 
		},
		handleSave() {
			this.$refs[this.formName].validate((valid) => {
				if (valid) {
					
				} else {
					
					return false;
				}
			});
		}
	},
	watch: {
		propVisible () {
			this.visible = this.propVisible;  
		},
		propDetail (){
			this.detail = this.copyData(this.propDetail);       
		},
		propDetailId () {
			if (this.propDetailId > 0) {
			}
		},
		propFormType () {
			this.formType = this.propFormType;
			if (this.formType === 1) {
				this.titleText = '添加';
			} else {
				this.titleText = '编辑';
			}

			this.clearValidate();
		}
	},
	beforeRouteUpdate (to, from, next) {
		// ...
	}
};

主要是实现新增和编辑共用一个对话框组件,重点是vue的updated()生命周期事件,表示在数据绑定(更新)完成后要处理的事情,此处在绑定(更新)数据完成后,取消验证所产生的一些红色提示,只在保存前验证。从而实现,在列表中,先选中某条记录编辑,然后再单击“添加”按钮,因为数据变化自动触发所产生的验证提示,使界面显示更友好。

猜你喜欢

转载自blog.csdn.net/XinShun/article/details/82349224