javascript - Vue JS, add event handler for elements created within JS -


i populating table inside axios api call , need add delete button each row.

im not quite sure how handle this, in current experience:

formattedvehicles.push([     "<div class='btn btn-danger' v-on:click='deletevehicle(id)'>delete</div>" ]); 

ofcourse, doesn't work. how go getting click handler delete button take parametre , handle method?

in vue.js don't have create div in jquery.

here have array of vehicles. template update when array change.

you need manage array of vehicles :

new vue({    el: "#app",    data: function() {      return {        formattedvehicles: [           { id: 1, name: 'vehi1' },           { id: 2, name: 'vehi2' },           { id: 3, name: 'vehi3' }        ]      }    },    methods: {      callingaxiosapi: function() {  //---> inside '.then(function (response) {' do:  //---> this.formattedvehicles = response; if response 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 can use 'id' 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 vehicle</button>    </div>      </div>

to understand code above :

use v-for when have list show in html :

v-for="(anynameyouwantforitemofarray, index) in yourarray" 

inside div contains v-for can access item of 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 component, key required.

to add event handler put v-on:click="method" or shortcut @click="method"

in case put <button @click="deletevehicle(vehicle.id, index)">delete vehicle</button> in v-for when clicked on button, call deletevehicle method index of row. in case can use id api call axios.

we use v-bind directive put javascript code in html attribute v-bind :

we in v-for have access index variable : v-bind:key="index" or shortcut ':' (a colon) : :key="index"


Comments