SoFunction
Updated on 2025-04-12

Detailed explanation of the steps to implement a table to dynamically add rows

Implementing a table that dynamically adds rows in Vue can be done by following the steps below.

Step 1: Set up the data model of the table

Define the data model of a table in the Vue component, and usually uses an array to store the data of the table. Each row of data can be an object, and the properties of the object correspond to the columns of the table.

data() {
  return {
    tableData: [
      { id: 1, name: 'John', age: 30 },
      { id: 2, name: 'Doe', age: 25 }
    ],
    newRow: { id: null, name: '', age: null } // Initial data of newly added rows  };
},

Step 2: Render the table

Use the v-for directive to traverse the table data and render the rows and columns of the table.

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Age</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(item, index) in tableData" :key="index">
      <td>{{  }}</td>
      <td>{{  }}</td>
      <td>{{  }}</td>
    </tr>
  </tbody>
</table>

Step 3: Add row function

Add a button to the template and trigger the function of adding new lines by clicking the button.

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

Implement the logic of adding rows in the Vue method.

methods: {
  addRow() {
    // Add new row data to the table data array    (({}, ));
  }
}

Complete sample code

&lt;template&gt;
  &lt;div&gt;
    &lt;table&gt;
      &lt;thead&gt;
        &lt;tr&gt;
          &lt;th&gt;ID&lt;/th&gt;
          &lt;th&gt;Name&lt;/th&gt;
          &lt;th&gt;Age&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/thead&gt;
      &lt;tbody&gt;
        &lt;tr v-for="(item, index) in tableData" :key="index"&gt;
          &lt;td&gt;{{  }}&lt;/td&gt;
          &lt;td&gt;{{  }}&lt;/td&gt;
          &lt;td&gt;{{  }}&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
    &lt;button @click="addRow"&gt;Add Row&lt;/button&gt;
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
  data() {
    return {
      tableData: [
        { id: 1, name: 'John', age: 30 },
        { id: 2, name: 'Doe', age: 25 }
      ],
      newRow: { id: null, name: '', age: null } // Initial data of newly added rows    };
  },
  methods: {
    addRow() {
      // Add new row data to the table data array      (({}, ));
    }
  }
};
&lt;/script&gt;

This implements a simple Vue table where rows can be added dynamically by clicking a button. In actual applications, you can expand according to your needs, such as supporting row editing and deletion functions, or dynamically updating new row data based on user input, etc.

This is the end of this article about Vue implementing a table that dynamically adds rows. For more information about Vue dynamically adds rows, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!