Vuejs, removing element from nested lists

Viewed 353

This is a followup question on VUEJS remove Element From Lists?, where they give various methods (this.$remove, splice, this.$delete) for dynamically removing a element from a list. I was trying to understand how to apply this to a nested loop; here's mine in three+ levels, somewhat stripped-down:

<template v-for="(labtype,index) in labIRlist">
  <template v-for="(lab,index2) in labtype">
    <tr v-for="(IR,index3) in lab.irs" :key="IR.irn">
      <td><p>{{ lab.hidtxt }}_{{ lab.mnem }}</p></td>
      <td><p>{{ lab.PNL }}</p></td>
      <td><p>{{ IR.provider}} {{ IR.psurv }}</p></td>
      <td><p>{{ IR.year }}-{{ IR.eventno }}</p></td>
      <td><p>{{ IR.analytes }}</p></td>
      <td><p>
        <button type="button" 
          @click="deleteIR(IR.irn,index,index2,index3)">
            DELETE
        </button>
      </p></td>
    </tr>
  </template>
</template>

Then there's Javascript for the deletion

methods: {
  deleteIR: function(IRNum,index,index2,index3) {
    // okay, delete!
    //... code to do something at the database...
    alert('IR successfully deleted!')
    // don't show the deleted IR any more
    this.labIRlist[index][index2].irs.splice(index3,1);
  },

Awful, but I didn't know how to identify the correct element. And it still didn't work (AFAIK it does nothing, no change visible to the row). How should this be done - don't we know the right element from where deleteIR was called?

1 Answers

What is the better way to handle deleting an element within multiple loops?

First of all, looking at how your template is built, we can assume that your data looks something like this:

  labIRlist: [
    [
      {
        hidtxt: "TEXT 1",
        irs: [{ provider: "provider1" }, { provider: "provider11" }],
        irn: "irn1",
      },
      {
        hidtxt: "TEXT 2",
        irs: [
          { provider: "provider2" },
          { provider: "provider22" },
          { provider: "provider222" },
        ],
        irn: "irn2",
      },
    ],
    [
      {
        hidtxt: "TEXT 3",
        irs: [{ provider: "provider3" }],
        irn: "irn3",
      },
    ],
  ],

If you want to delete one item from the nested irs array, all you need to do is to pass the irs array and the index of the item you want to delete, no need to do the whole path you are doing currently:

this.labIRlist[index][index2].irs.splice(index3,1);

So change your template to:

<button type="button" @click="deleteIR(lab.irs, index3)">

And the delete function is then simply:

deleteIR(IRS, index) {
  IRS.splice(index, 1);
}

A DEMO for your reference

PS. Please always share a bit of your data when posting questions like this. Much easier to answer when not needing to create your own sample data like I did here.

Related