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

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

0👍

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.

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>

Leave a comment