Why is the v-for directive malfunctioning and am I correctly displaying it in the template?

I'm new to working with Vuejs and recently created a mock dataset using JSON. The JSON file consists of an array containing 3 objects. Although console.log shows that Axios.get(URL) is fetching the data correctly, the v-for directive doesn't seem to be having any effect and I'm struggling to figure out why.

Below is the code for the Parent Component:

<template>
  <div class="home">
    <EventCard v-for="event in events" :key="event.id" :event="event" />
  </div>
</template>

<script>
import EventCard from "@/components/EventCard.vue";
import axios from "axios";
import { onBeforeMount } from "vue";

export default {
  name: "EventList",
  components: {
    EventCard,
  },
  setup() {
    let events = [];

    onBeforeMount(async () => {
      const res = await axios.get(
        "https://my-json-server.typicode.com/Tommydemian/real-world-vue-3/db"
      );
      const { data } = res;
      events = data.events;
      console.log(events);
    });

    return {
      events,
    };
  },
};
</script>

console.log: https://i.sstatic.net/S70JH.png

Code snippet for the Child Component which receives the prop:

<template>
  <div class="event-card">
    <span>@{{ event.time }} on {{ event.date }}</span>
    <h4>{{ event.title }}</h4>
  </div>
</template>

<script>
export default {
  name: "EventCard",
  props: {
    event: Object,
  },
  setup() {
    console.log();
  },
};
</script>

Answer №1

Updates must be a ref or reactive in order to be reactive within the template:

// UpdateList.vue         👇
import { onBeforeMount, ref } from 'vue'

export default {
  name: 'UpdateList',
  components: {
    UpdateCard,
  },
  setup() {       👇
    let updates = ref([])

    onBeforeMount(async () => {
      const response = await axios.get('https://my-json-server.typicode.com/Tommydemian/real-world-vue-3/db')
      const { responseData } = response
              👇
      updates.value = responseData.updates
      console.log(updates.value)
    })

    return {
      updates,
    }
  },
}

demo

Answer №2

When dealing with your console events, there is another object named events that requires you to assign data to res.events in order to access the main array of objects.

Make sure you are passing event instead of events.

<template>
  <div class="home">
    <EventCard v-for="event in events" :key="event.id" :event="event" />
  </div>
</template> 

Answer №3

To properly render the EventCard component, make sure to pass only the singular event as a prop instead of the entire collection events. The reason for this is that the parent component already handles looping through the data with v-for, so there's no need to do it again in the child component.

<EventCard :event="event" v-bind:key="event.id" />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Clear out the existing elements in the array and replace them with fresh values

Within my Progressive Web App, I am utilizing HTTP requests to populate flip cards with responses. The content of the requests relies on the selected values. An issue arises when I choose an item from the dropdown menu. It triggers a request and displays ...

What is the significance of `()=>` in JavaScript when using Selenium?

What is the significance of () => in the following sentence? ()=>{Object.defineProperties(navigator,{webdriver:{get:()=>false}})} I have only seen this syntax in JavaScript and it seems to be used for configuring page evaluation with Selenium. T ...

Exploring AngularJS ng-repeat features for custom attribute settings

I'm currently facing a challenge in removing multiple repetitive divs by utilizing ng-repeat. <!-- I have 21 of these --> <div class="table-row"> <span class="glyphicon glyphicon-wrench"></span> <label>Chlo ...

The Strapi registration feature in version 4 is giving a "method not allowed 405" error, which

Feeling a bit confused with a Strapi query. I am currently working on v4 and trying to set up a registration feature. The code snippet for invoking the function is provided below. Everything seems fine, such as submitting function variables, etc. However, ...

Issue with PHP form not saving data and correctly parsing output

I am facing an issue with my PHP page where it is supposed to grab responses from a form, insert the data into a table, and then display the response on the same page. I am using ajax to send form values without refreshing the page, but unfortunately, no i ...

Encountering a glitch while utilizing Nuxt 3 alongside the Nuxt Auth module

I'm currently working with nuxt 3 along with the nuxt auth module. Encountering this issue: https://i.sstatic.net/1iEz0.png Below is my nuxt configuration: export default defineNuxtConfig({ modules: [ '@nuxtjs/axios', ...

I'm receiving an error at initBackend that says "Cannot read properties of undefined (reading 'Vue'). Does anyone know how I can fix this issue?

In my Vue 3 application using Pinia for state management, I am facing a issue where newly added messages are not appearing on the screen. Additionally, there seems to be a persistent error in the Vue Devtools console. The application structure consists of ...

Using Vue.js to detect changes in a value and dynamically highlight the text

I am working on a simple script that generates random numbers every few moments. I want to change the background color whenever the random number is not equal to the one before it. Is this possible? For example, if the random numbers generated are 1, 1, an ...

Determine how to use both the "if" and "else if" statements in

/html code/ There are 4 textboxes on this page for entering minimum and maximum budget and area values. The condition set is that the maximum value should be greater than the minimum value for both budget and area. This condition is checked when the form i ...

What methods does MaterialUI utilize to achieve this?

Have you checked out the autocomplete feature in their component? You can find it here: https://mui.com/material-ui/react-autocomplete/ I noticed that after clicking on a suggestion in the dropdown, the input box retains its focus. How do they achieve thi ...

Navigating Angular: Discovering Route Challenges in Less Than an Hour

Can someone take a look at my code and help me out? I'm trying to learn Angular.js by following the popular Angular.js in 60 minutes video tutorial, but it seems like things have been updated since then. I'm having trouble getting my routes to wo ...

A single variable yields two distinct arrays

In the process of developing a script to extract the final lines from a csv file, which includes temperature data. The goal is to combine temperatures from file1 and file2 to determine the average temperature. Here's the current code snippet: v ...

Struggling with implementing a personalized zoom feature in React-Leaflet?

Looking to create a custom Zoom button using react-leaflet Below is the code I have been working on: import React from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { Map, TileLayer } from 're ...

Toggle Form Section Visibility

I am working on a table with five rows that have upload buttons. Each time I submit a row, the page refreshes, but I want to hide all but one row at a time. When the first submit button is clicked, it should show the next row and hide the previous ones. Th ...

The promise from the angular $http function is being duplicated

As I work on evaluating an expression within an if statement to return either true or false, I am utilizing $http promises. Despite the abundance of documentation available on this topic, I am confident in my ability to resolve any issues that may arise. ...

Using jQuery to remove an iframe upon a click event

My goal is to remove an iframe whenever anything on the page is clicked. I tried using this code: $('*').on('click',function(){ $('iframe').remove(); }); However, I encountered a problem where the i ...

Tips for extracting information from a JSON file using $routeParams in AngularJS

https://i.stack.imgur.com/NQCpy.png I am currently encountering an issue with retrieving data using $routeparams. Here is a description of my problem: Retrieving the URL to redirect console.log($routeParams); console.log($routeParams.json_url); $.getJS ...

Whenever the selected option in an HTML dropdown menu is modified, a corresponding input field should be automatically adjusted

Within my Rails application, I am facing a challenge related to updating the value of a text_field when a user chooses a different option from a select tag. The select tag is populated from a model which contains a list of countries for users to choose fro ...

In JavaScript, the function will return a different object if the string in an array matches the

My task involves working with a simple array of string ids and objects. Upon initial load, I am matching these Ids with the objects and setting the checked property to true. const Ids = ['743156', '743157'] [ { "id&quo ...

Convert price to Indonesian Rupiah currency format with the help of Vue.js

Can someone help me convert the price format from IDR 50,000.00 to IDR 50.000 using JavaScript and Vue? I found a script on this website, but I am having trouble understanding how it works. The script looks like this: replace(/(\d)(?=(\d{3})+(?: ...