elementui 两个slect关联
时间: 2023-09-01 10:07:39 浏览: 41
可以通过监听第一个 Select 组件的 change 事件,然后根据选中的值来动态更新第二个 Select 组件的选项。以下是一个示例代码:
```html
<template>
<div>
<el-select v-model="selectedOption1" @change="handleOption1Change">
<el-option
v-for="item in options1"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
<el-select v-model="selectedOption2">
<el-option
v-for="item in options2"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption1: '',
selectedOption2: '',
options1: [
{ label: 'Option 1-1', value: '1-1' },
{ label: 'Option 1-2', value: '1-2' },
{ label: 'Option 1-3', value: '1-3' },
],
options2: [],
optionMap: {
'1-1': [
{ label: 'Option 2-1', value: '2-1' },
{ label: 'Option 2-2', value: '2-2' },
],
'1-2': [
{ label: 'Option 2-3', value: '2-3' },
{ label: 'Option 2-4', value: '2-4' },
],
'1-3': [
{ label: 'Option 2-5', value: '2-5' },
{ label: 'Option 2-6', value: '2-6' },
{ label: 'Option 2-7', value: '2-7' },
],
},
};
},
methods: {
handleOption1Change() {
const selectedOption1 = this.selectedOption1;
if (selectedOption1) {
this.options2 = this.optionMap[selectedOption1];
if (!this.options2.find(item => item.value === this.selectedOption2)) {
this.selectedOption2 = '';
}
} else {
this.options2 = [];
this.selectedOption2 = '';
}
},
},
};
</script>
```
这里有两个 Select 组件,第一个是 options1,第二个是 options2。当 options1 的值发生变化时,会根据选中的值来动态更新 options2 的选项。同时,如果当前选中的选项在新的选项列表中不存在,就会自动清空第二个 Select 组件的值。