需求要求写有个动态表单,简单写了下,记录一下。
环境是vue2.0+element做的。主要是用到了component组件实现的。
vue代码:
<el-form ref="form" :model="current" label-width="80px" :rules="rules">
<el-row :gutter="24">
<template v-for="item in columns">
<el-col :span="12" :key="item.key" v-if="item.canView">
<el-form-item :label="item.value" :prop="item.key" :rules="item.rules">
<component :is="item.component" v-model="current[item.key]" v-bind="item.props" :disabled="!item.canEdit">
<template v-if="item.slot">
<template v-for="(child,index) in item.slot">
<component :is="child.component" v-bind="child.props" :key="index"></component>
</template>
</template>
</component>
</el-form-item>
</el-col>
</template>
</el-row>
</el-form>
- current对应当前form表单数据
- columns为渲染表单的数据源
- component的is对应渲染的组件名称(el-input)
- el-form-item上的rules对应表单的校验规则注意此处的prop为必填。否则校验不生效。
- v-bind绑定了组件的其他属性,可查询element-ui的api。所有参数均会传递给组件。
- component内部的component为部分组件需要插槽而存在如el-select,el-checkbox-group之类的
数据源:
this.columns = [{
key: 'date', // 必填
value: '日期', // 必填
width: '100',
fixed: 'left', // 'left' 'right' true 默认不固定
align: 'center', // 'left' 'center' 'right' 默认'left'
'header-align': 'center', // 'left' 'center' 'right' 默认继承align
canEdit: true, // 是否能编辑
canView: true, // 是否展示在form表单
required: false, // 是否必填 默认 false不必填
component: 'el-date-picker', // 使用的组件
props: {
type: 'date',
style: 'width: 100%',
placeholder: '请输入日期' // 提示词
},
rules: [
{ required: true, message: '日期不能为空' }
]
}, {
key: 'name',
value: '姓名',
canEdit: true, // 是否能编辑
canView: false, // 是否展示在form表单
component: 'el-input', // 使用的组件
props: {
type: 'input',
style: 'width: 100%',
placeholder: '请输入日期' // 提示词
}
}, {
key: 'address',
value: '地址',
canEdit: false, // 是否能编辑
canView: true, // 是否展示在form表单
component: 'el-input', // 使用的组件
props: {
type: 'textarea',
style: 'width: 100%',
placeholder: '请输入日期' // 提示词
}
}, {
key: 'addresss',
value: '地址1',
canEdit: true, // 是否能编辑
canView: true, // 是否展示在form表单
component: 'el-input', // 使用的组件
props: {
type: 'textarea',
style: 'width: 100%',
placeholder: '请输入日期' // 提示词
},
rules: { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
}, {
key: 'addressss',
value: '地址2',
canEdit: true, // 是否能编辑
canView: true, // 是否展示在form表单
component: 'el-select', // 使用的组件
props: {
style: 'width: 100%',
placeholder: '请输入日期' // 提示词
},
slot: [{
component: 'el-option',
props: {
label: '选项1',
value: 1
}
}, {
component: 'el-option',
props: {
label: '选项1',
value: 2
}
}]
}]