簡體   English   中英

如何動態添加一個在單擊時調用方法的html按鈕

[英]How to dynamically add an html button that calls a method on click

我有大量數據,並且正在使用數據表來顯示它。 在表格上,每一行都需要有一個按鈕,該按鈕將顯示具有該行中指定信息的模式。 由於數據表的行是在不使用vue的情況下制作的,因此似乎無法創建可以調用vue方法的html元素。 有沒有解決的辦法? 有沒有辦法我可以調用javascript函數?

我已經嘗試了很多事情,但我開始認為vue不允許這樣做。 我使用數據表而不是僅使用vue表的原因是因為它是一個非常大的數據集,而數據表將使導航變得更加容易。

任何想法或建議,將不勝感激。 我對vue和datatable相當陌生。 謝謝!

const foo = (elmName, text) => {
  let button = document.createElement(elmName);
  button.innerHTML = text;
  button.onclick = () => {
      alert('dynamic');
      return false;
   };
    return button
  };

  document.body.appendChild(foo('button', 'Click It'));

這就是我要做的

<template>    
    <div v-show="showUpdateModal">
        my modal HTML
    </div>
    <div v-show="showDeleteModal">
        my modal HTML
    </div>

    <table>
      <thead>
        <th>No</th>
        <th>Name</th>
        <th>Email</th>
        <th>Action</th>
      </thead>
      <tbody>
        <tr
          v-for="(customer, index) in customers"
          :key="customer.id">
          <td>{{ index+1 }}</td>
          <td>{{ customer.name }}</td>
          <td>{{ customer.email }}</td>
          <td>
            <button @click="openUpdateModal(customer.id)">
              <i class="fa fa-edit"></i>
            </button>
            <button @click="openDeleteModal(customer.id)">
              <i class="fa fa-trash-alt"></i>
            </button>
          </td>
        </tr>
      </tbody>
    </table>
</template>

它創建調用函數的按鈕,並將customer.id作為參數傳遞。

然后在腳本中,我可以添加

<script>
export default {
    data () {
       return {
          customers: [], // array of customer from database
          showUpdateModal: false, // will open modal when it is true
          showDeleteModal: false,
       }
    },
    methods: {
       openUpdateModal (id) {
          this.showUpdateModal = true
       }
       openDeleteModal (id) {
          this.showDeleteModal = true
       }
    }
}
</script>

暫無
暫無

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

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