v-select 来自数据的分组来自 api

v-select with groups from data via api

我从我的 API 中得到这个数据:

[
   {
      "id":69,
      "name":"Baupraxis",
      "upper_id":7
   },
   {
      "id":42,
      "name":"bautipps.de",
      "upper_id":4
   },
   {
      "id":16,
      "name":"Bellevue",
      "upper_id":7
   },
   {
      "id":18,
      "name":"besser Bauen",
      "upper_id":7
   },
   {
      "id":2,
      "name":"Besuch auf Betriebsgel\u00e4nde",
      "upper_id":0
   },
   {
      "id":7,
      "name":"billiger Bauen",
      "upper_id":0
   }
]

我用它来填充一个 v-select 像这样:

<v-select
 label="Anfrageart"
 dense
 :items="itemsRequestTypes"
 item-text="name"
 item-value="id"
 v-model="requestType"
>
</v-select>

所以这就是我要解决的问题,如果 upper_id 是具有匹配项 id 的项目的子组,则它大于零。 upper_id 中的方法是主要组的 id

现在如何将其分组到 v-select 中? 我尝试在 object 中添加一个 header,但这没有帮助。

您需要先转换 API 中的数据,然后再将其传递给模板。此外,v-select 支持使用 items 的嵌套选项组,其中 header 类型表示组 header,即 non-selectable 项。

const data = [
  {
    "id": 69,
    "name": "Baupraxis",
    "upper_id": 7
  },
  {
    "id": 42,
    "name": "bautipps.de",
    "upper_id": 4
  },
  {
    "id": 16,
    "name": "Bellevue",
    "upper_id": 7
  },
  {
    "id": 18,
    "name": "besser Bauen",
    "upper_id": 7
  },
  {
    "id": 2,
    "name": "Besuch auf Betriebsgel\u00e4nde",
    "upper_id": 0
  },
  {
    "id": 7,
    "name": "billiger Bauen",
    "upper_id": 0
  }
];

// Create an intermediate object to hold categories.
const groups = {};

// Create array for each group to main subgroup list.
data.forEach((x) => {
  // create empty object if it doesn't exists.
  groups[x.upper_id] = groups[x.upper_id] || { name: x.name, list: [] };
  
  groups[x.upper_id].list.push(x);
});

// The flattened list of items that holds items as well as unique headers
const flattened = [];

// Iterate over all the unique categories and
// then flatten into a list that v-select needs.
Object.keys(groups).forEach((categoryId) => {
  const catgory = groups[categoryId];
  const categoryName = category.name;

  // Create a group 
  flattened.push({ header: categoryName });

  // Add all the items followed by category header
  flattened.push(...category.list);
});