vue3下拉框去重
时间: 2025-05-23 11:40:39 浏览: 21
### Vue3 中实现下拉框选项去重功能
在 Vue3 的项目中,可以通过 JavaScript 提供的 `Set` 对象或者数组的高阶函数(如 `reduce` 或者 `filter`)来轻松实现数据去重。以下是基于 Element Plus 组件库的一个完整解决方案。
#### HTML 结构
```html
<template>
<el-select v-model="selectedValue" style="width:220px;" multiple collapse-tags placeholder="请选择岗位">
<el-option v-for="item in uniquePostOptions" :key="item.post_name" :label="item.post_name" :value="item.post_name"></el-option>
</el-select>
</template>
```
#### 脚本部分
```javascript
<script>
import { ref, onMounted } from 'vue';
export default {
setup() {
const selectedValue = ref([]);
const postOptions = ref([
{ post_name: '前端工程师' },
{ post_name: '后端工程师' },
{ post_name: '全栈工程师' },
{ post_name: '前端工程师' }, // 重复项
{ post_name: '测试工程师' }
]);
// 使用 Set 去重逻辑
const uniquePostOptions = computed(() => {
const seen = new Set();
return postOptions.value.filter(item => {
if (seen.has(item.post_name)) {
return false;
} else {
seen.add(item.post_name);
return true;
}
});
});
return {
selectedValue,
postOptions,
uniquePostOptions
};
}
};
</script>
```
上述代码实现了以下几点:
1. 定义了一个原始未处理的数据列表 `postOptions`[^1]。
2. 利用 Vue3 的响应式特性以及计算属性 `computed` 来生成一个新的无重复数据的列表 `uniquePostOptions`[^4]。
3. 将最终的结果渲染到 `<el-select>` 和 `<el-option>` 上,从而展示给用户一个干净、不带重复选项的下拉菜单。
这种方法不仅简单易懂,而且充分利用了现代框架的能力,无需手动绑定额外的事件监听器即可完成视图更新与模型同步[^2]。
#### 备注说明
如果需要从远程 API 获取数据并对其进行去重,则可以在请求成功后的回调函数里加入类似的去重操作:
```javascript
async function fetchData() {
try {
const response = await fetch('https://example.com/api/posts');
const data = await response.json();
// 远程数据本地化存储前先做去重处理
const obj = {};
const filteredData = data.reduce((accumulator, current) => {
if (!obj[current.post_name]) {
accumulator.push(current);
obj[current.post_name] = true;
}
return accumulator;
}, []);
postOptions.value = filteredData;
} catch (error) {
console.error('Error fetching posts:', error);
}
}
onMounted(fetchData);
```
此片段展示了如何在网络请求完成后立即对返回的数据执行过滤动作,并将其赋值回组件的状态变量之中[^3]。
阅读全文
相关推荐












