封装一个element-ui el-form组件,接收一个对象数组,对象属性有
时间: 2024-05-11 17:13:54 浏览: 114
label、value、type、options等,用于渲染表单元素。同时支持表单验证和表单提交。
示例代码:
```vue
<template>
<el-form ref="form" :model="form" :rules="rules" label-width="100px">
<el-form-item v-for="item in items" :key="item.label" :label="item.label" :prop="item.value">
<el-input v-if="item.type === 'text'" v-model.trim="form[item.value]" :placeholder="item.placeholder"></el-input>
<el-select v-else-if="item.type === 'select'" v-model.trim="form[item.value]" :placeholder="item.placeholder">
<el-option v-for="option in item.options" :key="option.value" :label="option.label" :value="option.value"></el-option>
</el-select>
<el-date-picker v-else-if="item.type === 'date'" v-model.trim="form[item.value]" :placeholder="item.placeholder" type="date"></el-date-picker>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">提交</el-button>
</el-form-item>
</el-form>
</template>
<script>
export default {
props: {
items: {
type: Array,
required: true
}
},
data() {
return {
form: {},
rules: {}
}
},
mounted() {
this.items.forEach(item => {
this.form[item.value] = ''
if (item.required) {
this.rules[item.value] = [{ required: true, message: item.label + '不能为空', trigger: 'blur' }]
}
})
},
methods: {
submitForm() {
this.$refs.form.validate(valid => {
if (valid) {
this.$emit('submit', this.form)
}
})
}
}
}
</script>
```
使用方式:
```vue
<template>
<dynamic-form :items="formItems" @submit="handleSubmit"></dynamic-form>
</template>
<script>
import DynamicForm from './DynamicForm.vue'
export default {
components: {
DynamicForm
},
data() {
return {
formItems: [
{ label: '用户名', value: 'username', type: 'text', placeholder: '请输入用户名', required: true },
{ label: '密码', value: 'password', type: 'text', placeholder: '请输入密码', required: true },
{
label: '性别',
value: 'gender',
type: 'select',
placeholder: '请选择性别',
options: [
{ label: '男', value: 'male' },
{ label: '女', value: 'female' }
],
required: true
},
{ label: '生日', value: 'birthday', type: 'date', placeholder: '请选择生日', required: true }
]
}
},
methods: {
handleSubmit(form) {
// 处理表单提交逻辑
}
}
}
</script>
```
阅读全文