簡體   English   中英

Vue.js 中的事件監聽器

[英]Event Listener in Vue.js

我目前正在使用 Vue.js 構建一個小型警報應用程序。 我想在具有“del”類的按鈕上有一個 eventListener 來調用方法並移交事件,我為此使用了 Vue 的“掛載”功能:

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

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

在該方法中,我想獲取單擊的按鈕的 id 並對其進行處理:

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

我花了幾個小時弄清楚出了什么問題,但我無法理解。

編輯:我想這樣做的方式很重要,因為按鈕是動態列表的一部分,通過 v-html 呈現。 這是將 HTML 添加到數據變量的方法:

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>";
  }

這就是使用 v-html 指令呈現變量的方式:

<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>

我不確定如何使用事件偵聽器方法,但我認為將 v-for 指令與 vue 模板一起使用將允許您執行所需的操作。

<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>

然后,您可以修改deleteAlarm()函數以刪除該行或從alarms數組中刪除該項目。

此示例演示了一個事件偵聽器和一個綁定。

<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);
      }
    }
})

更新:我更新了小提琴以演示綁定和偶數偵聽器。

這是一個小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM