I'm currently building a small alarm application with Vue.js. I want to have an eventListener on buttons with a class of "del" that calls a method and hands over the event, I'm using Vue's "mounted" feature for that:
mounted: function timeInterval () {
var app = this;
var del = document.getElementsByClassName("del");
del.addEventListener('click', function (e) {
app.deleteAlarm(e);
},
}
In that method I want to get the id of the button that was clicked and do something with it:
deleteAlarm: function (e) {
var app = this;
var id = e.target.id;
app.alarms.splice(id, 1);
}
I spent hours on figuring out what's going wrong but I can't get it.
Edit: The way I want to do this is important, because the buttons are part of a dynamic list, that gets rendered via v-html. This is the method that adds the HTML to the data variable:
getAlarmList: function () {
var app = this;
app.alarmTable = '';
for (let i=0; i<app.alarms.length; i++) {
app.alarmTable += "<tr><td>"+app.alarms[i][0]+"</td><td>"+app.alarms[i][1]+":"+app.alarms[i][2]+":"+app.alarms[i][3]+"</td><td><button type=\"button\" id=\""+i+"\" class=\"btn btn-dark btn-sm del\">Löschen</button></td></tr>";
}
And this is how the variable gets rendered out with the v-html directive:
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Time</th>
<th></th>
</tr>
</thead>
<tbody v-html="alarmTable">
</tbody>
</table>
I'm not sure how to go about the event listener approach, but I think using the v-for directive with a vue template would allow you to do what you need.
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Time</th>
<th></th>
</tr>
</thead>
<tbody v-html="alarmTable">
<template v-for="(alarm, index) in alarms">
<tr>
<td>{{ alarm[0] }}</td>
<td>{{ alarm[1] }}:{{ alarm[2] }}:{{ alarm[3] }}</td>
<td>
<button
type="button"
v-on:click="deleteAlarm(index)"
class="btn btn-dark btn-sm"
>
Löschen
</button>
</td>
</tr>
<template>
</tbody>
</table>
Then you could workshop your deleteAlarm()
function to either delete the row, or delete the item from the alarms
array.
This example demonstrates an event listener and a binding.
<div id="app">
<button v-on:click="del" id="1" class="deletable">Foo</button>
<button v-on:click="del" id="2" class="deletable">Bar</button>
</div>
new Vue({
el: '#app',
mounted () {
this.$el.querySelectorAll('.deletable').forEach( (button) => {
button.addEventListener('click', (e) => {
console.log("delete from event handler:" + e.target.id);
})
} );
},
methods: {
del (e) {
console.log("delete from a method:" + e.target.id);
}
}
})
Update : I updated the fiddle to demo both, the binding and an even listener.
Here is a Fiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.