简体   繁体   English

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

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

I have a big set of data, and I'm using datatables to display it. 我有大量数据,并且正在使用数据表来显示它。 On the table, each row needs to have a button that will display a modal with the specified info from the row. 在表格上,每一行都需要有一个按钮,该按钮将显示具有该行中指定信息的模式。 Since the rows of the datatable are made without using vue, it doesn't appear I can create an html element that can call a vue method. 由于数据表的行是在不使用vue的情况下制作的,因此似乎无法创建可以调用vue方法的html元素。 Is there a way around this? 有没有解决的办法? Is there a way I can just call a javascript function? 有没有办法我可以调用javascript函数?

I have tried many things and I'm starting to think vue will not allow this. 我已经尝试了很多事情,但我开始认为vue不允许这样做。 The reason I'm using datatables instead of just a vue table, is because it is a very large data set and datatables would make it much easier to navigate. 我使用数据表而不是仅使用vue表的原因是因为它是一个非常大的数据集,而数据表将使导航变得更加容易。

Any thoughts or advice on this would be appreciated. 任何想法或建议,将不胜感激。 I am fairly new to vue and datatables. 我对vue和datatable相当陌生。 Thanks! 谢谢!

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

This Is what I do 这就是我要做的

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

It creates button that calls function and passes customer.id as parameter. 它创建调用函数的按钮,并将customer.id作为参数传递。

Then in script, I can add 然后在脚本中,我可以添加

<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