Listening to Events in Vue.js

I am currently in the process of developing a small alarm application using Vue.js. My goal is to add an eventListener to buttons with the "del" class that triggers a method and passes over the event. To achieve this, I am utilizing Vue's "mounted" feature:

mounted: function timeInterval () {
    var app = this;

    var del = document.getElementsByClassName("del");
    del.addEventListener('click', function (e) {
      app.deleteAlarm(e);
    },
}

Within the deleteAlarm method, my objective is to extract the id of the clicked button and perform actions based on it:

deleteAlarm: function (e) {
  var app = this;
  var id = e.target.id;
  app.alarms.splice(id, 1);
}

I've spent considerable time trying to troubleshoot the issue but haven't been successful in resolving it.

Note: The approach I am taking is crucial as the buttons are part of a dynamic list rendered through v-html. Here is the function responsible for adding HTML content 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>";
  }

Furthermore, this is how the variable gets displayed utilizing 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>

Answer №1

One possible solution could involve utilizing the v-for directive within a Vue template in conjunction with an event listener. This approach would likely enable you to achieve the desired functionality for your project.

<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"
          >
            Delete
          </button>
        </td>
      </tr>
    <template>
  </tbody>
</table>

To further enhance this solution, you can refine your deleteAlarm() function to effectively remove either the row or the corresponding item from the alarms array.

Answer №2

This illustration showcases the implementation of an event listener along with a binding.

<div id="app">
<button v-on:click="remove" id="1" class="deletable">Foo</button>
<button v-on:click="remove" id="2" class="deletable">Bar</button>
</div>

new Vue({
    el: '#app',
    mounted () {
      this.$el.querySelectorAll('.deletable').forEach( (button) => {
      button.addEventListener('click', (e) => {
      console.log("deletion from the event handler:" + e.target.id);  
      })
      } );
    },
    methods: {
        remove (e) {
        console.log("deletion via a method:" + e.target.id);
      }
    }
})

Enhancement: The fiddle has been modified to exhibit both, the binding and an event listener simultaneously.

Here is the Updated Fiddle

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to update a value in Angular's HTML binding?

I'm working with some HTML code <div ng-bind-html="safeHtml"></div> <button ng-click="refresh()">refresh</button> What should the refresh function look like in order to update the value? ...

Utilize an asynchronous method to upload files to Google Cloud Storage in a loop

I am new to using Javascript and have been working on a loop to upload images to Google Cloud Storage. While the image uploads correctly with this code, I'm facing an issue where the path (URL) is not being saved in the database AFTER the upload. I a ...

Unlock the power of json data traversal to derive cumulative outcomes

Our goal is to populate a table by parsing a JSON object with predefined header items. (excerpt from an answer to a previous query) var stories = {}; for (var i=0; i<QueryResults.Results.length; i++) { var result = QueryResults.Results[i], ...

The React page on localhost is displaying a void of content with just a white background, no elements are

Can someone help me figure out what I'm doing wrong with my codes? I recently used a website called robohash to generate random robot images based on the text provided. For example, robohash.org/test was utilized in my code. The command prompt indic ...

Tips for resetting the form input fields in Vue.js after the user has successfully submitted the form

I am facing an issue with my registration page. After the user enters some values and successfully submits the form, I want to clear all the fields. To achieve this, I am using a predefined function called reset() inside the script section. However, the ...

What is the best way to extract and process CSV data from a JavaScript array of strings to incorporate into d3 visualizations?

I am looking to utilize data stored in a JavaScript array of strings to create a d3 graph that showcases a time series of timestamp (t), receive (rx), and transmit (tx) counters. Each element in the array represents one line of time, rx, tx data with comma ...

.npmignore failing to exclude certain files from npm package

I'm facing an issue with a private module on Github that I am adding to my project using npm. Despite having a .npmignore file in the module, the files specified are not being ignored when I install or update it. Here is what my project's packag ...

Unable to resolve parameters for ApplicationModule: (?) in Angular 7 Just-in-Time compilation

I am currently experiencing an issue that seems to occur randomly, despite everything working perfectly in my setup. I have several Angular applications compiled with webpack. They all work fine in AOT mode but crash in JIT mode. This is because the compi ...

Incorporating Java project dependencies into an npm project

I'm facing a challenge in my development process, where I need to incorporate dependencies from a Maven Java project into my package.json file within my Vue/Typescript project. These dependencies are crucial for accessing specific data types that my p ...

Can someone show me how to create a JavaScript countdown with a Unix timestamp?

I'm in the process of building a website that requires a countdown to a specific time, but I'm struggling to find a solution that allows me to input a Unix timestamp and display the same countdown for all users, irrespective of their time zones. ...

Converting HTML to a Text String (not for display) using Angular

When it comes to displaying HTML in Angular, there are numerous approaches available. For example, using $sce.trustAsHtml(myHtmlVariable) is one way to achieve this. However, I am interested in creating something like the following: myStringVariable = s ...

Submitting data to a PHP script using AJAX and the $_POST method

I'm attempting to transfer data from my AJAX request into a PHP $_POST variable in order to update my database. HTML <form id="23" method="post"> <select name="admin" onchange="chosenadmin(23)"> <option value="rick">rick&l ...

How can I utilize this.$apollo within a Vuex store using vue-apollo in a NUXT environment?

I am trying to save the user data from a login action in the vuex store, but I am unable to access this.$apollo. export const actions = { UPSERT_USER({ commit }, { authUser, claims }) { this.$apollo .mutate({ mutation: UPSERT_USER ...

Concealing and revealing the sidebar container

I created a website here and needed to implement a button in the header to hide and show the sidebar. Unfortunately, my current code is not working. Here is what I have attempted: <div id="B"> <button>toggle</button> </div> $ ...

Is it possible to unit test a Vuex getter that accesses the store in conjunction with Jest?

Currently, I am attempting to test a simple getter function from my Vuex store that concatenates two strings together: const getters = { addressToGet: state => { return state.baseAddress + store.getters.queryToGet } } I have no trouble mocking ...

Activate mouseover function automatically for each feature on the leaflet

I'm facing a challenging situation where I need to develop a dashboard application that is similar to the functionality of ChoroplethExample. However, the catch is that I have to loop through all states (Features in geoJSON) and pause for 3 seconds at ...

What is the best way to retrieve environment variables from an NPM package in an Angular 5 application

Is there a method for my node module, created from an Angular 5 application, to access the environment variable from the Angular 5 application (environments/environment.ts)? Perhaps Angular 5 exports its environment variables to JavaScript global variables ...

What is the simplest way to run a basic express js script?

I am encountering an issue while trying to run a basic express script in JavaScript. Every time I attempt to execute the script, I keep getting an error message stating that "require is not defined". Below are snippets of the code. Thank you! const expres ...

Learn how to showcase video information in a vue.js template

I am having difficulty displaying a saved media (video) file on another page after collecting it using the ckeditor5 media option. The data is stored along with HTML tags generated by ckeditor, so I'm using v-html to display other content like <p&g ...

Can you explain the variances between the index.html and index-async.html files within the AngularJS seed project?

Within the angularjs seed project, there are two files that appear to produce identical results: index.html and index-async.html. If you want to view the code for index-async.html, you can visit this link. Similarly, if you're interested in the code ...