DEV Community


Posted on

A Vue3 Tutorial - 02 Tables

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.

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 },
Enter fullscreen mode Exit fullscreen mode

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.

        <tr v-for="worker in workers">
Enter fullscreen mode Exit fullscreen mode

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">
Enter fullscreen mode Exit fullscreen mode

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)