Apply methods to item in v-for array Vue 3 JS

49 Views Asked by At

It must be very simple but I can't figure out how to access the values of an item in a v-for array in Vue 3.

<template>
  <div>
    <table class="table-auto w-full max-w-screen mt-4">
      <thead>
        <tr>
          <th>Name</th>
          <th>Surname</th>
          <th>Email</th>
        </tr>
      </thead>
      <tbody>
        <template v-for="request in pending">
          <tr>
            <td>{{ request.name }}</td>
            <td>{{ request.surname }}</td>
            <td>{{ request.email }}</td>
            <td>
              <button
                class="text-white bg-green-800 rounded-md px-2 py-2"
                @click="sendApproval"
                >Approve</button
              >
            </td>
            <td>
              <button class="text-white bg-red-800 rounded-md px-2 py-2">Reject</button>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      pending: [],
      form: {
        name: '',
        surname: '',
        email: '',
      },
      index: '',
    };
  },

  mounted() {
    this.getPending();
  },
  methods: {
    getPending() {
      axios
        .get('/api/pending/')
        .then((response) => {
          console.log('data', response.data);
          this.pending = response.data;
        })
        .catch((error) => {
          console.log('error', error);
        });
    },

    sendApproval() {
      this.form.name = request.name;
      console.log(this.form.name);
    },
  },
};
</script>


SO basically I get a response from an API (using axios) and I add each item (named 'request' in my code) received in a list named "pending".

Using v-for, I display in a table all the values of each request from the pending list.

Then I would like to be able to click on 'Approve' to call the method sendApproval()that would take the request values to add them to a form that would later be sent back using axios (POST method).

The problem is that I cannot access each request values using v-for.

I have tried using v-bind but it is not working.

What am I doing wrong please? How to add the request values to the form?

Thank you

1

There are 1 best solutions below

0
On

The individual request won't be sent to the method unless you pass it as a parameter. The method should also define a paremeter to receive that value.

@click="sendApproval(request)"
sendApproval(request) {
  this.form.name = request.name;
  console.log(this.form.name);
},