时间:2022-11-30 10:58:17 | 栏目:vue | 点击:次
vue 实现动态表单/动态渲染组件的方式(一),供大家参考,具体内容如下
三个表单组件,用了element-ui
此处用了自定义组件的v-model来收集子组件的数据
//InputComponent.vue 要渲染的子组件 <template> <el-input :value="username" @input="inputHandler"></el-input> </template> <script> export default { name: 'InputComponent', data() { return { } }, model: { prop: 'username', event: 'input' }, props: { username: String }, methods: { inputHandler(ev) { console.log(ev) this.$emit('input', ev) } } } </script> <style scoped> </style>
//SwitchComponent.vue 要渲染的子组件 <template> <el-switch :value="checked" active-color="#13ce66" inactive-color="#ff4949" @change="changeHandler" > </el-switch> </template> <script> export default { name: 'SwitchComponent', data() { return { } }, model: { prop: 'checked', event: 'change' }, props: { checked: { default: true } }, methods: { changeHandler(ev) { this.$emit('change', ev) } } } </script> <style scoped> </style>
//SelectComponent.vue 要渲染的子组件 <template> <el-select :value="role" placeholder="请选择" @change="changeHandler"> <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.label"> </el-option> </el-select> </template> <script> export default { name: 'SelectComponent', data () { return { options: [ { value: '1', label: '李世民' }, { value: '2', label: '嬴政' }, { value: '3', label: '刘邦' }, { value: '4', label: '项羽' }, { value: '5', label: '范蠡' } ], value: '' } }, model: { prop: 'role', event: 'change' }, props: { role: { default: '' } }, methods: { changeHandler(ev) { this.$emit('change', ev) } } } </script> <style scoped> </style>
主组件(父组件)
此处用了自定义组件的v-model来收集子组件的数据
//Main.vue 父组件 <template> <div> <el-form :model="formData"> <el-form-item v-for="(item, index) in formItemList" :key="index" :label="item.label"> <component :is="item.type" v-model="formData[item.key]" > </component> </el-form-item> </el-form> </div> </template> <script> //引入三个表单组件 import InputComponent from './subComponents/InputComponent' import SelectComponent from './subComponents/SelectComponent' import SwitchComponent from './subComponents/SwitchComponent' export default { name: 'Main', data() { return { //数据的type值要与组件的名字对应 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: { } } }, components: { InputComponent, SwitchComponent, SelectComponent, }, methods: { } } </script> <style scoped lang="less"> </style>