vue防止数据过滤,污染原数据
通过一级渠道下拉框接口获取数据,用户选择一级渠道时,动态过滤并显示与选中一级渠道parent相匹配的二级渠道数据。所有business以逗号连接存储。若用户先选二级渠道后改选一级,则filteredOptions存储新过滤的二级数据,确保二级下拉框与当前一级选择关联。提交时,二级选择独立,不依赖一级选择。案例
<template>
<div>
一级渠道<el-select v-model="selectedValue" placeholder="请选择" @change="handleValueChange">
<el-option
v-for="item in options"
:key="item.business"
:label="item.label"
:value="item.business"
/>
</el-select>
二级渠道<el-select v-model="selectedValue2" placeholder="请选择" @change="handleValue2Change">
<el-option
v-for="item in filteredOptions2"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
<el-button @click="resetOptions">重置选项</el-button>
</div>
</template>
<script>
export default {
data() {
return {
options: [],
options2: [],
selectedValue: '',
selectedValue2: '',
filteredOptions2: []
}
},
created() {
this.initializeOptions()
},
methods: {
initializeOptions() {
// 初始化 options 和 options2
this.options = [{
business: 1,
value: '选项1',
label: '黄金糕1'
}, {
business: 2,
value: '选项2',
label: '双皮奶1'
}, {
business: 3,
value: '选项3',
label: '蚵仔煎1'
}, {
business: 4,
value: '选项4',
label: '龙须面1'
}, {
business: 5,
value: '选项5',
label: '北京烤鸭1'
}]
this.options2 = [{
business: 1,
value: '张三',
label: '黄金糕'
}, {
business: 2,
value: '李四',
label: '双皮奶'
}, {
business: 3,
value: '王五',
label: '蚵仔煎'
}, {
business: 4,
value: '赵六',
label: '龙须面'
}]
this.filteredOptions2 = [...this.options2] // 初始时显示全部 options2
},
handleValueChange(value) {
this.selectedValue2 = ''
// 根据 value 过滤 options2
this.filteredOptions2 = this.options2.filter(item => item.business === value)
},
handleValue2Change(value) {
// 可以添加对 value2 变化的响应,但这里不改变 filteredOptions2
},
resetOptions() {
// 重置 options2 为初始状态
this.filteredOptions2 = [...this.options2]
}
}
}
</script>