时间:2022-08-23 10:23:48 | 栏目:vue | 点击:次
本文实例为大家分享了vue实现动态表单动态渲染组件的方式,供大家参考,具体内容如下
//主页面 <template> <el-form :model="formData"> //把从后端取到的数据传给子组件,动态生成slot插槽列表 <FormItemSlot :formItemList="formItemList"> <el-form-item label="开关" slot="switch-component"> <el-switch v-model="formData.checked" active-color="#13ce66" inactive-color="#ff4949" > </el-switch> </el-form-item> <el-form-item label="名字" slot="input-component"> <el-input v-model="formData.username"></el-input> </el-form-item> <el-form-item label="角色" slot="select-component"> <el-select v-model="formData.role" placeholder="请选择"> <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.label"> </el-option> </el-select> </el-form-item> </FormItemSlot> </el-form> </template> <script> improt 引入slot列表子组件 FromItemSlot(下面有) export default { data() { return { formItemList: [ { type: 'switch-component', require: true, label: '开关', key: 'isOpen' }, { type: 'input-component', require: true, label: '姓名', key: 'name' }, { type: 'select-component', require: true, label: '角色', key: 'role' }, ], formData: { }, options: [ { value: '1', label: '李世民' }, { value: '2', label: '嬴政' }, { value: '3', label: '刘邦' }, { value: '4', label: '项羽' }, { value: '5', label: '范蠡' } ], } }, components: { FormItemSlot }, } </script>
//FormItemSlot.vue 插槽列表 <template> <div class="slot-wrap"> <slot v-for="(item, index) in formItemList" :name="item.type"></slot> </div> </template> <script> export default { name: 'FormItemSlot', props: { formItemList: { type: Array, default() { return [] } } } } </script> <style scoped> </style>
以上数据会直接收集到formData中,此方式的好处在于表单数据都在一个页面,方便数据处理.