Vue.js中如何根据数组唯一id在select选项中展示对应关联数据
Vue 组件分类关联产品下拉实现方案
核心逻辑
先定义分类类型和产品类型的映射规则,再通过Vue计算属性根据选中的分类动态过滤符合要求的产品列表即可。
完整代码实现
Vue 3 SFC 示例
<template> <div> <!-- 分类选择下拉 --> <select v-model="selectedCategory"> <option value="">请选择分类</option> <option v-for="cate in categories" :key="cate.id" :value="cate" > {{ cate.name }} </option> </select> <!-- 关联产品下拉 --> <select v-model="selectedProduct" v-if="filteredProducts.length"> <option value="">请选择产品</option> <option v-for="product in filteredProducts" :key="product.id" :value="product" > {{ product.name }} </option> </select> </div> </template> <script setup> import { ref, computed } from 'vue' // 从DB获取的原始数组 const categories = ref([]) const products = ref([]) // 选中值绑定 const selectedCategory = ref(null) const selectedProduct = ref(null) // 分类type对应展示的产品type规则,可根据业务扩展 const productTypeMapping = { 'A': ['B', 'C', 'D'], 'B': ['X', 'Y', 'Z'] } // 动态过滤产品列表 const filteredProducts = computed(() => { if (!selectedCategory.value) return [] // 获取当前分类允许展示的产品type列表 const allowTypes = productTypeMapping[selectedCategory.value.type] || [] // 过滤规则:parent_id匹配选中分类id + 产品type在允许列表内 return products.value.filter(item => { return item.parent_id === selectedCategory.value.id && allowTypes.includes(item.type) }) }) </script>
Vue 2 适配写法
export default { data() { return { categories: [], products: [], selectedCategory: null, selectedProduct: null, productTypeMapping: { 'A': ['B', 'C', 'D'], 'B': ['X', 'Y', 'Z'] } } }, computed: { filteredProducts() { if (!this.selectedCategory) return [] const allowTypes = this.productTypeMapping[this.selectedCategory.type] || [] return this.products.filter(item => { return item.parent_id === this.selectedCategory.id && allowTypes.includes(item.type) }) } } }
可选调整
- 不需要匹配parent_id、仅根据分类type展示全局对应type产品的话,删掉过滤规则里的
item.parent_id === selectedCategory.value.id即可 - 需要按产品type分组展示的话,用
<optgroup>标签包裹同类型产品,新增分组计算属性即可:
const groupedProducts = computed(() => { const group = {} filteredProducts.value.forEach(item => { group[item.type] = group[item.type] || [] group[item.type].push(item) }) return group })
内容的提问来源于stack exchange,提问作者Ashraful Alam Shihab
相关产品推荐
相关产品推荐

