vue elementui 封装组件 此组件根据configjs动态展示input或者select或switch
以下是一个简单的示例,展示如何根据config.js动态展示不同类型的表单组件:
<template>
<el-form ref="form" :model="form" :rules="rules" label-width="80px">
<el-form-item v-for="(item, index) in config" :key="index" :label="item.label" :prop="item.prop">
<component :is="getComponent(item.type)" v-model="form[item.prop]" :options="item.options"></component>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">提交</el-button>
</el-form-item>
</el-form>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
data() {
return {
form: {},
rules: {},
config: [
{
label: '输入框',
prop: 'input',
type: 'input',
},
{
label: '下拉框',
prop: 'select',
type: 'select',
options: [
{ value: 'option1', label: '选项1' },
{ value: 'option2', label: '选项2' },
{ value: 'option3', label: '选项3' },
],
},
{
label: '开关',
prop: 'switch',
type: 'switch',
},
],
};
},
computed: {
...mapGetters(['getComponent']),
},
methods: {
submitForm() {
this.$refs.form.validate(valid => {
if (valid) {
// 表单验证通过,提交表单数据
} else {
// 表单验证不通过,做相应处理
}
});
},
},
};
</script>
// config.js
export default {
input: {
type: 'input',
label: '输入框',
prop: 'input',
},
select: {
type: 'select',
label: '下拉框',
prop: 'select',
options: [
{ value: 'option1', label: '选项1' },
{ value: 'option2', label: '选项2' },
{ value: 'option3', label: '选项3' },
],
},
switch: {
type: 'switch',
label: '开关',
prop: 'switch',
},
};
// store.js
import config from './config.js';
export default {
state: {
componentMap: {
input: 'el-input',
select: 'el-select',
switch: 'el-switch',
},
},
getters: {
getComponent: state => type => state.componentMap[type],
},
// ...
};
上述示例中,config.js中定义了不同类型的表单组件配置,包括输入框、下拉框和开关。在Vue组件中,根据config.js动态生成表单项,并使用<component>标签根据不同的type属性渲染相应的表单组件。同时,通过Vuex的getters实现了根据type获取对应的组件名,这样可以方便地扩展和维护配置和组件的映射关系
原文地址: https://www.cveoy.top/t/topic/hXOE 著作权归作者所有。请勿转载和采集!