Search code examples
javascriptvue.jsv-for

Remove duplicate list item in v-for


I'm retrieving all groups from an axios request at the page load and I store that data inside an empty array inside a reactive object like this,

const groupHandler = reactive({
    groups: [],
});

And when the user clicked one of his product and click on edit a form will appear like this,

enter image description here

Here you can see Group 1 has been repeated. And there is another reactive object to store that user's product's group id,

const productForm = reactive({
   group: 2,
});

So when the user clicks on a product productForm.group will be filled with that product's group id. I want to prevent this been duplicated in my edit product form. I'm using the v-for directive to loop the groups array,

<li
    v-for="group in groupHandler.groups"
    :key="group.id"
    :group-id="group.id" >
      {{ group.name }}
</li>

So how to prevent this duplicate? In the v-for directive, I could use a condition like if group.id is not equal to productForm.group print group.name But I have no clue to do this. Really appreciate if somebody could help thanks.


Solution

  • You can use v-for in the template element, and then in the li element, you can use v-if condition to only render the group which doesn't have that id

    <template v-for="group in groupHandler.groups">
    <li
        v-if="group.id !== productForm.group"
        :key="group.id"
        :group-id="group.id" >
          {{ group.name }}
    </li>
    </template>