Ychop
Ychop

Reputation: 27

Getting index from Array in Vue.js

I'm trying to remove an entry in my array "joke" by clicking on the removeButton right next to the entry of the list. I think it should be possible, that if i can somehow pass the id from the entry (in which the removeButton was clicked) to my remove function then this would solve my problem, but how?

the code:

  <div>
    <ul>
      <li v-for="jokes in joke" :key="jokes.title" class="joke">
        <p class="title">{{ jokes.title }}</p>
        <p>{{ jokes.text }} (Id:{{ jokes.id }})</p>
        <v-btn icon @click="remove" id="removeButton><v-icon>mdi-sticker-remove-outline</v-icon></v-btn>
      </li>
    </ul>
  </div>

<script>
export default {
  name: "Liste",
  props: ["joke"],
  data: function() {
    return {

    };
  },

  methods: {
    remove: function() {
      this.$emit("removeEntry", {
       //here i want to pass the right id
      });
    },
  },
};
</script>

this is how the joke Array looks:

[{"id":"1","title":"title1","text":"a joke","rating":"4"},
{"id":"2","title":"title2","text":"funny joke","rating":"5"},
{"id":"3","title":"title3","text":"Nanother funny joke","rating":"2"}]

So for example i want to delete the Joke with the id="2",then i would click on the removeButton which is placed next to the joke entry in the List and i want to get the id 2 if the removeButton next to the entry was clicked to delete the entry from my Json array(i implemented this function in a other component, so here my only problem is to get the right id).

I hope i could discribe my problem clearly, if not feel free to ask me :) Thank you Guy in advance :) , lof you <3

Upvotes: 1

Views: 798

Answers (2)

Javlon Khalimjanov
Javlon Khalimjanov

Reputation: 80

Everyting goes fine. Simple thing you should add , is an argument to your removeButton function .

Here how it might look like:

removeButton(id){
   this.jokes.splice(id, 1);
}

And then in your template pass jokes.id as an argument

Upvotes: 1

palaѕн
palaѕн

Reputation: 73896

In the remove button pass the joke id like:

<v-btn icon @click="remove(jokes.id)"

and then update the method like:

methods: {
  remove: function(id) {
    this.$emit("removeEntry", {
      id: id
    });
  },
},

Or, you can pass the id directly also:

methods: {
  remove: function(id) {
    this.$emit("removeEntry", id);
  },
},

Upvotes: 2

Related Questions