Ask Your Question
4

How can I populate a table using Vue.js 3 and the Composition API?

asked 2023-04-29 07:07:35 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-04-29 07:15:01 +0000

huitzilopochtli gravatar image

To populate a table using Vue.js 3 and the Composition API, you can follow these steps:

  1. Create a component for your table and import the necessary libraries:
<template>
  <div>
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Age</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in items" :key="index">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import { ref } from "vue";
import axios from "axios";

export default {
  name: "Table",
  setup() {
    const items = ref([]);
    axios.get("https://api.example.com/data").then((response) => {
      items.value = response.data;
    });

    return { items };
  },
};
</script>
  1. Add a ref for your data and fetch the data using Axios:
import { ref } from 'vue'
import axios from 'axios'

export default {
  setup() {
    const items = ref([])

    axios.get('/api/data').then((response) => {
      items.value = response.data
    })

    return { items }
  }
}
  1. Use v-for to loop through the data and populate the table:
<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Age</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(item, index) in items" :key="index">
      <td>{{ item.id }}</td>
      <td>{{ item.name }}</td>
      <td>{{ item.age }}</td>
    </tr>
  </tbody>
</table>

That's it! Now you have a table populated with data using Vue.js 3 and the Composition API.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-04-29 07:07:35 +0000

Seen: 14 times

Last updated: Apr 29 '23