Add rows to the table dynamically with the use of vue.js

To dynamically add rows to a table in Vue.js, you can follow these steps:

  1. In your Vue component's data, define an array to hold the rows of the table. For example, you can have a data property called "rows" that is initially an empty array.

  2. Create the table structure in your template, including the table header and an empty tbody element. You can use the v-for directive to iterate over the "rows" array and generate the table rows dynamically.

  3. Add a button or any element that triggers the addition of a new row to the table. For example, you can have a button with a click event handler.

  4. In the event handler method, push a new object representing a row into the "rows" array. This will automatically update the table in the template due to Vue's reactivity system.

Here is an example implementation:

<template>
  <div>
    <table>
      <thead>
        <tr>
          <th>Column 1</th>
          <th>Column 2</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="row in rows" :key="row.id">
          <td>{{ row.column1 }}</td>
          <td>{{ row.column2 }}</td>
        </tr>
      </tbody>
    </table>

    <button @click="addRow">Add Row</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rows: []
    };
  },
  methods: {
    addRow() {
      this.rows.push({ column1: '', column2: '' });
    }
  }
};
</script>

In the above example, clicking the "Add Row" button will add a new row to the table with empty values for the "Column 1" and "Column 2" cells. You can modify the addRow method to pre-fill the columns with default values or fetch data from an API, depending on your requirements.