Delete elements from array

I want to stop displaying(delete it) an element after the button is clicked. I do understand that following the indexes might cause problems, so is it possible to remove the element based on its key instead?

Recipes

<div v-for="recipe in recipies" v-bind:key="recipe.id">
  <SingleRecipe v-bind:recipe="recipe" v-on:del-recipe="deleteRecipe" />
</div>
----
data() {
  return {
    recipes: [],
    index: null
  }
}, 
methods: {
  deleteRecipe(id) {
      this.recipes = this.recipes.splice(id, 1);
    }
}

and SingleRecipe

 <button @click="$emit('del-recipe', this.id)">Delete this recipe</button>

The SingleRecipe is the child and Recipes is the parent.
Thank you for your help, I don’t have a lot of experience :slight_smile:

I found a similar query here: V-for and deleting components but I cannot get my head around it… :frowning:

The splice method returns an array with all removed elements, so assigning the return value to this.recipes does not work:

this.recipes = this.recipes.splice(...);
// recipes is now an array with all deleted recipes 

The splice method mutates the original object so you don’t need to reassign the array:

this.recipes.splice(...);
// recipes is now mutated, without reassigning it

But splice works by index and you don’t have the index - you have the id. You have multiple options:

  • You can find the index using findIndex and then remove it with splice
  • You can filter the array using the filter method (see here). Note: Unlike splice the filter method does not mutate the original array but create a new one instead, so you need to assign the return value to this.recipes

I personally prefer the second approach. Read the docs, try it for yourself and ask again if you need help.

Alright, thank you! I did actually manage to pass the index to the child
(

v-for="(recipe, inx) in recipes ...
  <SingleRecipe :recipe="recipe" :index="inx"

)
and used splice but now I will try to figure out how to do it with filter. :slight_smile: