Lovelock
Lovelock

Reputation: 8085

Vue JS, add event handler for elements created within JS

I am populating a table inside an Axios API call and need to add a delete button to each row.

Im not quite sure how to handle this, in my current experience:

formattedVehicles.push([
    "<div class='btn btn-danger' v-on:click='deleteVehicle(id)'>Delete</div>"
]);

Ofcourse, this doesn't work. How do I go about getting a click handler for the delete button to take a parametre and handle it as a method?

Upvotes: 1

Views: 4027

Answers (1)

Happyriri
Happyriri

Reputation: 4443

In Vue.js you don't have to create div like in jQuery.

Here you have an array of vehicles. The template will update when the array change.

You just need to manage the array of vehicles like this :

new Vue({
  el: "#app",
  data: function() {
    return {
      formattedVehicles: [
         { id: 1, name: 'vehi1' },
         { id: 2, name: 'vehi2' },
         { id: 3, name: 'vehi3' }
      ]
    }
  },
  methods: {
    callingAxiosApi: function() {
//---> Inside your '.then(function (response) {' you do:
//---> this.formattedVehicles = response; If response is the array of vehicles
    },
    addVehicle: function() {
      var rand = Math.floor(Math.random() * (100 - 4)) + 4;
      this.formattedVehicles.push({ id: rand, name: 'vehi' + rand });
    },
    deleteVehicle: function(id, index) {
//---> Here you can use 'id' to do an Axios API call.
      this.formattedVehicles.splice(index, 1);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script>
<div id="app">
  
  <button @click="addVehicle">Add vehicle</button>
  
  <div v-for="(vehicle, index) in formattedVehicles" :key="index">
    id: {{ vehicle.id }}
    <br />
    name: {{ vehicle.name }}
    <button @click="deleteVehicle(vehicle.id, index)">Delete this vehicle</button>
  </div>
  
</div>

To understand the code above :

Use v-for when you have a list to show in html :

v-for="(anyNameYouWantForItemOfArray, index) in yourArray"

Inside the div that contains the v-for you can access the item of the aray : {{ vehicle.id }}, {{ vehicle.name }} or pass data in event handler : @click="deleteVehicle(vehicle.id, index)"

You must use key property in v-for since version 2.2.0+ key :

In 2.2.0+, when using v-for with a component, a key is now required.

To add event handler you just put v-on:click="method" or the shortcut @click="method"

In this case we put <button @click="deleteVehicle(vehicle.id, index)">Delete this vehicle</button> in the v-for so when we clicked on the button, we call the deleteVehicle method with the index of the row. In your case you can use id to do an API call with axios.

We use the v-bind directive to put javascript code in html attribute v-bind :

We are in the v-for so we have access to index variable : v-bind:key="index" or with the shortcut ':' (a colon) : :key="index"

Upvotes: 6

Related Questions