需求:需要根据类型type动态显示某些参数,并且后端需要的参数也不同,比如type为1:后端要aa和bb参数,type为2:后端要cc和dd参数,前端显示的字段名也不一样,但是样式是不变的。
1.效果
2.主要代码讲解
因为vue的限制,所以需要使用this.$set让数组变为响应式,不然会导致输入框输入不了
handleChange(value) {
let params = {
1: [
{
label: '姓名',
name: ''
},
{
label: '年龄',
age: ''
}
],
2: [
{
label: '开始时间',
start: ''
},
{
label: '结束时间',
end: ''
}
]
};
this.$set(this.formObj, 'paramsList', params[value]);
},
这句话的意思就是在对象中找到不是label的属性
v-model="formObj.paramsList[index][Object.keys(item).find((key) => key !== 'label')]"
可以打印一下输出,结果是name
let aa = Object.keys({
label: '姓名',
name: ''
}).find((key) => key !== 'label');
console.log(aa);//name
3.完整代码
<!--
* @Description:
* @Author: guoxiaxue
* @Date: 2025-04-27 14:56:56
* @FilePath: \vue-secondMenu-test-master\src\page\test4\zongti\01.Deepseek.vue
-->
<template>
<div style="margin-top: 40px">
<el-select v-model="selectedOptions" clearable placeholder="请选择" @change="handleChange">
<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
</el-select>
<el-form :model="formObj" ref="addBaseRef" label-width="95px" class="demo-ruleForm add-point-form" style="margin: 40px 0px">
<el-descriptions labelClassName="labelClassName" direction="vertical" :column="5" border style="width: 500px">
<el-descriptions-item :label="item.label" v-for="(item, index) in formObj.paramsList" :key="item.label" :span="1">
<el-form-item
:prop="`paramsList[${index}].${Object.keys(item).find((key) => key !== 'label')}`"
:rules="[
{
required: true,
message: '',
trigger: 'blur',
message: `请输入${item.label}`
}
]"
label-width="0px"
>
<el-input
style="width: 167px"
size="small"
v-model="formObj.paramsList[index][Object.keys(item).find((key) => key !== 'label')]"
:placeholder="`请输入${item.label}`"
></el-input>
</el-form-item>
</el-descriptions-item>
</el-descriptions>
</el-form>
<el-button type="primary" @click="submitForm('addBaseRef')">立即创建</el-button>
</div>
</template>
<script>
export default {
data() {
return {
formObj: {
paramsList: []
},
selectedOptions: 1,
options: [
{
value: 1,
label: '参数1'
},
{
value: 2,
label: '参数2'
}
]
};
},
mounted() {
this.handleChange(this.selectedOptions);
},
methods: {
handleChange(value) {
let params = {
1: [
{
label: '姓名',
name: ''
},
{
label: '年龄',
age: ''
}
],
2: [
{
label: '开始时间',
start: ''
},
{
label: '结束时间',
end: ''
}
]
};
this.$set(this.formObj, 'paramsList', params[value]);
},
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
}
}
};
</script>
<style lang="scss" scoped></style>
文章到此结束希望对你有所帮助~