Now that we have the basics, let's wire up a table. The scenario would be that we get data from some data source and we want to have it display in a table. We also want to search on this table, sort this table and maybe even make a few selections about what to display.
For now, however let's just get the table working.
https://github.com/Krowemoh/vue3-without-build
The Data
The first step is to wire in the data. We are going to fake the data for now, so we can just add in a list into our data function.
(The data was take from the datatables site, great library.:))
data() {
return {
name: 'Nivethan',
workers: [
{ name: "Airi Satou", position: "Accountant", office: "Tokyo", age: 33},
{ name: "Angelica Ramos", position: "Chief Executive Officer (CEO)", office: "London", age: 47 },
{ name: "Cedric Kelly", position: "Senior Javascript Developer", office: "Edinburgh", age: 22 },
{ name: "Jennifer Chang", position: "Regional Director", office: "Singapore", age: 28 },
],
}
}
We create an array called workers and now we can use this in the main html.
The View
Now that we have the data available, it's time to display it.
<table>
<thead>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
</thead>
<tbody>
<tr v-for="worker in workers">
<td>{{worker.name}}</td>
<td>{{worker.position}}</td>
<td>{{worker.office}}</td>
<td>{{worker.age}}</td>
</tr>
</tbody>
</table>
This is pretty straightforward html, the only thing that should give you pause is the v-for tag. This is like the curly brackets from before. The v-for tag takes in a loop and inside it looks like you can use javascript variable names. This is a bit weird as it's inside the quotes so I'm curious if traditional ranges and calculations work inside the quotes. It could be that v-for attribute is quite limited.
The v-for tag is going to create as many rows as there are workers. We can get the index if we need it by doing the following.
<tr v-for="(worker, index) in workers">
Now if we refresh the page we should see a table with out users! Usually I would use a function to hold a template string and then loop and build up that string and then append it to the dom. This is already loads better than that strategy. I really like this style of being able to embed the template logic directly into the html rather than have it be in the javascript.
Top comments (0)