How to separate data in a v-for with Vue.js 3?

Viewed 38

With Vue.js 3 and the draggable package I'm creating a list of grid elements which I want to separate with Category dividers.


Headline 1


---- Grid Elements with Category "headline1"


Headline 2


---- Grid Elements with Category "headline".

What's the problem?

My current way is working, but I think it needs a lot of improvement. Here I share which way I go currently:

<template>
  <div class="element-container">
    <h2>Headline 1</h2>
    <draggable 
      v-model="getElementsForCurrentRole" 
      group="headline1" 
      @end="save" 
      item-key="name">
      <template #item="{element}">
        <n-card v-if="element.category == 'headline1'" class="brf-element" :class="'brf-' + element.name" :title="formatElementName(element.name)" size="small" header-style="{titleFontSizeSmall: 8px}" hoverable>
          <n-switch v-model:value="element.active" @update:value="save(element)" size="small" />
        </n-card>
      </template>
    </draggable>

    <h2>Headline 2</h2>
    <draggable 
      v-model="getElementsForCurrentRole" 
      group="headline2" 
      @end="save" 
      item-key="name">
      <template #item="{element}">
        <n-card v-if="element.category == 'headline2'" class="brf-element" :class="'brf-' + element.name" :title="formatElementName(element.name)" size="small" header-style="{titleFontSizeSmall: 8px}" hoverable>
          <n-switch v-model:value="element.active" @update:value="save(element)" size="small" />
        </n-card>
      </template>
    </draggable>
  </div>
</template>

As you can see, I create multiple for loops iterating the same array. I separate the elements just by showing only specific elements with the needed category (v-if="element.category == 'something').

But: When I have 50 categories, I need 50 for loops. And I loop trough the exact same array each time. I think there is a better solution. What would be the best practice here?

Edit

Tried the tipps from Lawrence Cherone's comment. It works and its much less code. Great. But: what does not work (and also did not work before I guess) is the indexing. When I drag elements from the second category, the elements from the first changes their position. What's the issue here?

<div v-for="cat of elementCategories" :key="cat">
  <h4>{{cat}}</h4>
  <draggable 
    v-model="getElementsForCurrentRole" 
    group="{{cat}}" 
    @end="save" 
    item-key="name">
    <template #item="{element}">
      <n-card v-if="element.category == cat" class="brf-element" :class="'brf-' + element.name" :title="formatElementName(element.name)" size="small" header-style="{titleFontSizeSmall: 8px}" hoverable>
        <n-switch v-model:value="element.active" @update:value="save(element)" size="small" />
      </n-card>
    </template>
  </draggable>
</div>
0 Answers
Related