Wisamx
Wisamx

Reputation: 303

How can I access vue repeated item key from a method

I have an html page, which has a table and an iterated row using v-for:

<table id="app-4">
  <tr v-for="(item, index) in results" :key="item.id">
    <td>@{{ item.title }}</td>
    <td>
       <button v-on:click="deleteItem(index)">Delete</button>
    </td>
  </tr>
</table>

and I have this js code.

var app4 = new Vue({
  el: '#app-4',
  data: {
    results: []
  },
  methods: {
    deleteItem: function (index) {
        this.results.splice(index,1);
        //Can I access item key and tr properties from here and the delete button
    }
  },
  mounted() {
    axios.get('api.list.url').then(response => {
        this.results = response.data;
    })
  }
});

In the deleteItem function, Can I access item key and tr properties and append text to the item delete button.

Upvotes: 0

Views: 146

Answers (1)

Stephen Thomas
Stephen Thomas

Reputation: 14053

The traditional Vue approach would probably be to use references

<table id="app-4">
  <tr v-for="(item, index) in results" :key="item.id" ref="rows">
    <td>@{{ item.title }}</td>
    <td>
       <button v-on:click="deleteItem(index)" ref="deleteButtons>
           Delete
       </button>
    </td>
  </tr>
</table>

And in the code

deleteItem: function (index) {
    this.results.splice(index,1);
    //Can I access item key and tr properties from here?

    // Yes, e.g. to get the text content of the first cell
    const text = this.$refs.rows[index].cells[0].textContent.trim();

    // And add it to the delete button text
    this.$refs.deleteButtons[index].textContent += " " + text;
}

Of course, that example is a bit nonsensical since you know the item's title, but the principle works for other properties of the text row (e.g. attributes, computed styles, classes, etc.)

Upvotes: 1

Related Questions