Append new data to table with vue
In Vue.js, you can append new data to a table by using the push()
method to add new data to an array, and then updating the table using a v-for
loop. Here's an example:
HTML
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr v-for="person in people" :key="person.id">
<td>{{ person.name }}</td>
<td>{{ person.age }}</td>
</tr>
</tbody>
</table>
JavaScript
export default {
data() {
return {
people: [
{ id: 1, name: 'John', age: 25 },
{ id: 2, name: 'Jane', age: 30 }
]
}
},
methods: {
addPerson(newPerson) {
this.people.push(newPerson);
}
}
}
In this example, we have a people
array that contains objects with id
, name
, and age
properties. We use a v-for
loop to render the table rows.
To append new data to the table, we define a addPerson
method that takes a new person object as an argument. We use the push()
method to add the new person to the people
array.
To call the addPerson
method, you can use a button or a form to submit the new data. For example:
<button @click="addPerson({ id: 3, name: 'Bob', age: 35 })">Add Person</button>
This will add a new person object to the people
array and update the table accordingly.
Note: Make sure to use a unique id
property for each person object, so that Vue can correctly identify and update the table rows.
Alternatively, you can use a Vue.set()
method to add new data to the table. This method is useful when you need to add new data to an array that is already being used in a v-for
loop.
Vue.set(this.people, this.people.length, newPerson);
This method will add the new person object to the end of the people
array and update the table accordingly.