Home > Mobile >  Why is this v-for not rendering properly and Am I returning it properly in the template?
Why is this v-for not rendering properly and Am I returning it properly in the template?

Time:06-18

I'm quite new to Vuejs, just created a fake dataset with json. The file contains an array of 3 objects. When I check on console.log I could understand that the Axios.get(URL) is fetching the data properly, but the v-for seems to have no effect and I'm not able to understanding why it is happening.

Here's the code (Parent Component):

<template>
  <div >
    <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: enter image description here

code (Child Component) which receives the prop:

<template>
  <div >
    <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>

CodePudding user response:

on your console events has another object called events you need to assign data to res.events to access the main array of objects

you are passing events instead of event

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


   

CodePudding user response:

You just need to pass event as props in EventCard and not events. Since events is the collection of data. It has to be looped again once taken into the child component as props. Since you are looping events in the parent component. It is better to pass only the event through props.

<EventCard v-for="event in events" :key="event.id" :event="event" />
  • Related