search

Home  >  Q&A  >  body text

Vue 3: v-for shows more components than items

<p>I'm new to Vue and trying out a few things. I'm also using Ionic and new to this too. I have my own component <trip.card> and I want to display each trip instance returned from the API. </p> <pre class="brush:php;toolbar:false;"><template> <ion-page> <ion-content :fullscreen="true"> <ion-header collapse="condense"> <ion-toolbar> <ion-title size="large">Woadie - Trips</ion-title> </ion-toolbar> </ion-header> <trip-card v-for="trip in trips" ref="trips" :tripName="trip.name" /> </ion-content> </ion-page> </template></pre> <p>From what I understand from the documentation, I can now use onMounted to set my data. </p> <pre class="brush:php;toolbar:false;"><script setup lang="ts"> import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar, } from "@ionic/vue"; import TripCard from "./TripCard.vue"; import axios from "axios"; import { ref, onMounted } from "vue"; const trips = ref([]); onMounted(() => { axios.get("http://localhost:8081/woadie/trips").then((response) => { trips.value = response.data; }); }); </script></pre> <p>Right now, my API returns an array containing a trip instance. However, the <trip-card> component is displayed far more than once. What could be the reason for this? </p><p>In the documentation I found the following code snippet. </p><p><br /></p> <pre class="brush:php;toolbar:false;"><script setup> import { ref, onMounted } from 'vue' const list = ref([ /* ... */ ]) const itemRefs = ref([]) onMounted(() => console.log(itemRefs.value)) </script> <template> <ul> <li v-for="item in list" ref="itemRefs"> {{ item }} </li> </ul> </template></pre> <p>The difference between my implementation and the documentation seems to be const list = ref([]) and <li v-for="item in list" ref="itemRefs"> instead of using itemRefs directly . Why this extra step? What does this extra step do? It's not explained in the documentation and I don't understand why this is needed. </p>
P粉245276769P粉245276769488 days ago549

reply all(1)I'll reply

  • P粉727531237

    P粉7275312372023-07-29 12:47:01

    ref="itemRefs" will contain all <li> rendered by v-for. instead of your list elements.

    This is called a template ref:


    https://vuejs.org/guide/essentials/template-refs.html

    reply
    0
  • Cancelreply