<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="app">
<button @click="addSelect">add</button>
<div v-for="select in selectList" class="item">
<div class="label">{{ select.label }}</div>
<select v-model="select.value">
<option v-for="option in getOptionList(select.value)" :value="option.value">
{{ option.label }}
</option>
</select>
</div>
selectList: {{selectList}} <br />optionList:{{optionList}}
</div>
<script src="./vue3.js"></script>
<script>
// https://unpkg.com/vue@3/dist/vue.global.js
Vue.createApp({
data() {
return {
optionList: [],
selectList: [],
};
},
computed: {
// 其他下拉框已经选中的值,需要在当前下拉框不展示,遍历时,只要在这个数组里就要去掉
selectedValue() {
const set = new Set();
this.selectList.forEach((item) => set.add(item.value));
console.log('set,', set);
return set;
},
},
methods: {
addSelect() {
this.selectList.push({
label: '新增下拉框',
value: '',
});
},
/**
* 核心函数:这个函数,需要在非选择的下拉框的时候去理解
*/
getOptionList(val) {
console.log('888,', val);
let res = this.optionList.filter((item) => {
// 传过来的值!==遍历到的数据源item,并且,其他下拉框已经选中了
if (val !== item.value && this.selectedValue.has(item.value)) return false;
return true;
});
console.log('res,', res);
return res;
},
},
mounted() {
for (let i = 0; i < 5; i++) {
this.optionList.push({
label: '选项' + i,
value: 'option' + i,
});
}
for (let i = 0; i < 2; i++) {
this.selectList.push({
label: '下拉框' + i,
value: '',
});
}
},
}).mount('#app');
</script>
</body>
</html>
vue,多个下拉框,使用同一个数据源,实现下拉数据不被重复选择(隐藏其他选中的数据)
于 2023-05-25 16:36:05 首次发布