Vue之 根据下拉框选项选择的不同动态显示不同的表单数据 配置
- 定义下拉框选项和对应的表单数据:
data() {
return {
options: [
{ label: '选项一', value: 'option1' },
{ label: '选项二', value: 'option2' },
{ label: '选项三', value: 'option3' }
],
option1Data: { // 选项一对应的表单数据
name: '',
age: '',
...
},
option2Data: { // 选项二对应的表单数据
email: '',
phone: '',
...
},
option3Data: { // 选项三对应的表单数据
address: '',
city: '',
...
},
formData: {} // 当前选中的表单数据
}
}
- 在模板中渲染下拉框和表单数据:
<template>
<div>
<select v-model="formData" @change="handleChange">
<option v-for="option in options" :value="option.value">{{ option.label }}</option>
</select>
<div v-if="formData === 'option1'">
<input v-model="option1Data.name">
<input v-model="option1Data.age">
...
</div>
<div v-if="formData === 'option2'">
<input v-model="option2Data.email">
<input v-model="option2Data.phone">
...
</div>
<div v-if="formData === 'option3'">
<input v-model="option3Data.address">
<input v-model="option3Data.city">
...
</div>
</div>
</template>
- 在组件中定义
handleChange方法,根据选中的下拉框选项更新当前表单数据:
methods: {
handleChange() {
if (this.formData === 'option1') {
this.formData = this.option1Data;
} else if (this.formData === 'option2') {
this.formData = this.option2Data;
} else if (this.formData === 'option3') {
this.formData = this.option3Data;
}
}
}
``
原文地址: https://www.cveoy.top/t/topic/fzbo 著作权归作者所有。请勿转载和采集!