Vue2+ElementUI表单、Form组件的封装
在Vue2和ElementUI中,可以通过封装一个自定义组件来封装表单处理逻辑。以下是一个简单的封装示例:
<template>
<el-form
ref="form"
:model="formData"
:rules="rules"
:label-width="labelWidth"
>
<slot />
<el-form-item v-if="showSubmitButton">
<el-button type="primary" @click="submitForm">提交</el-button>
</el-form-item>
</el-form>
</template>
<script>
export default {
name: 'MyForm',
props: {
formData: Object,
rules: Object,
labelWidth: {
type: String,
default: '100px'
},
showSubmitButton: {
type: Boolean,
default: true
}
},
methods: {
submitForm() {
this.$refs.form.validate((valid) => {
if (valid) {
this.$emit('submit', this.formData);
} else {
this.$message.error('表单验证失败!');
}
});
}
}
};
</script>
使用方法:
<template>
<my-form :form-data="form" :rules="rules" ref="myForm">
<el-form-item label="用户名" prop="username">
<el-input v-model="form.username"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input type="password" v-model="form.password"></el-input>
</el-form-item>
</my-form>
</template>
<script>
import MyForm from './MyForm.vue';
export default {
components: {
MyForm
},
data() {
return {
form: {
username: '',
password: ''
},
rules: {
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{ min: 6, max: 12, message: '密码长度在 6 到 12 个字符', trigger: 'blur' }
]
}
};
}
};
</script>
在这个封装中,MyForm
组件接收formData
和rules
作为prop,并提供一个插槽,以便父组件可以添加自定义的表单项。submitForm
方法用于触发表单验证并在验证通过后通过自定义事件向父组件发送数据。
评论已关闭