Home » vue » Vue.js Axios: How to call method from an HTML component passing an argument

Vue.js Axios: How to call method from an HTML component passing an argument

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m facing an issue when calling an axios function from an HTML component. I’d need to call the function passing as parameter the “user.id” from the iteration:

<tr v-for="user in users" :key="user.id">
    <td>{{user.id}}</td>
    <td>{{user.name}}</td>
    <td>{{user.surname}}</td>
    <td>  <button class="button"  @click="delete(user.id)">Delete</button></td>
</tr>

From the function, I can send a DELETE request for that user.id.

methods: {
    delete: function(id) {

         alert('I am deleting " +id)
         // Delete here
    },

It seems I have multiple problems here, and the first one is that, from the logs:

avoid using JavaScript unary operator as property name: "delete(user.id)" in expression @click="delete(user.id)"

In the end, the function delete is not even called. I wonder if there’s a way to get around this issue.
Thanks

Answers:

Log clears itself

avoid using JavaScript unary operator as property name

delete is an operator defined in JavaScript.
Reference – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

Choose any other name for your method

Try deleteUser as your method name

<tr v-for="user in users" :key="user.id">
    <td>{{user.id}}</td>
    <td>{{user.name}}</td>
    <td>{{user.surname}}</td>
    <td>  <button class="button"  @click="deleteUser(user.id)">Delete</button></td>
</tr>

methods: {
    deleteUser: function(id) {

         alert("I am deleting " +id)
         // Delete here
    },