如何动态添加一个在单击时调用方法的html按钮

时间:2018-09-17 20:46:29

标签: javascript vue.js datatables vuejs2

我有大量数据,我正在使用数据表来显示它。在表格上,每一行都需要有一个按钮,该按钮将显示具有该行中指定信息的模式。由于数据表的行是在不使用vue的情况下制作的,因此似乎无法创建可以调用vue方法的html元素。有没有解决的办法?有没有办法我可以调用javascript函数?

我尝试了很多事情,并且开始认为vue不允许这样做。我使用数据表而不是仅使用vue表的原因是因为它是一个非常大的数据集,而数据表将使其更易于浏览。

任何对此的想法或建议,将不胜感激。我对vue和datatable相当陌生。谢谢!

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

这就是我要做的

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