In this article, we will learn how to fetch and iterate over data in Vue.
Vue3 is an excellent frontend framework that tries to mitigate the drawbacks of the existing frontend frameworks.
It follows a templating to render elements to the DOM and recommends encapsulating the complete component logic in a single file, from the script to styles to the HTML elements.
Variables are defined using ref
in Vue that will help us to persist the data, we will define this variable in the script and then define a function that will fetch the data and update the variable.
After that in the template will iterate over the data and render the list.
<script setup> import { ref } from "vue"; const todos = ref(null); async function fetchData() { const res = await fetch("https://jsonplaceholder.typicode.com/todos"); let data = await res.json(); todos.value = data; } fetchData(); </script> <template> <div> <div v-if="!todos">Loading...</div> <div v-if="todos"> <ul> <li v-for="todo in todos" :key="todo.id"> {{ todo.title }} </li> </ul> </div> </div> </template>
As we are using template, the conditional logic and rendering logic are handled as attributes on the DOM element.