Data fetching with lifecycle hooks

Contrast the approach of fetching data within the created hook in Options API versus the setup function in Composition API.
// Options API approach

new Vue({
  el: '#app',
  data() {
    return {
      items: []
  created() {
    // Data fetching would generally happen here
      .then(response => response.json())
      .then(data => {
        this.items = data;
      .catch(error => console.error('Error fetching data:', error));
In the Options API approach, the 'created' lifecycle hook is used to fetch data as soon as the Vue instance is created. The 'this' context refers to the Vue instance itself, allowing the fetched data to be assigned directly to the 'items' data property.
// Composition API approach

import { ref, onMounted } from 'vue';

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

    onMounted(async () => {
      try {
        const response = await fetch('');
        items.value = await response.json();
      } catch (error) {
        console.error('Error fetching data:', error);

    return {
In the Composition API, the setup function is executed before the component is created. The 'onMounted' lifecycle hook is used instead to ensure the DOM has been mounted before fetching data. The 'ref' function creates a reactive reference for data that updates the template when changed.