Search code examples
javascriptvue.jsvuejs3v-for

Vue 3 How to dynamically load data from server and show in a v-for loop


I want to dynamically showing data from from the database in a v-for loop. However, if I try to push the new data into the array, they are displayed correctly in a console.log(), but nothing changes in the template.

I made a simplified representation of this in Codepen:

<template>
  <ul v-for="number in numbers">
    <li>{{ number.num }} : {{ number.text }}</li>
  </ul>
  {{ numbers }}
</template>

<script setup>
let numbers = [
  { num: 1, text: "One" },
  { num: 2, text: "Two" },
  { num: 3, text: "Three" }
];

// simulate server
setTimeout(() => {
  numbers.push({ num: 4, text: "Four" });
  console.log(numbers); // returns the array correct
}, 3000);
</script>

Link to the Snippet: https://codepen.io/Tenarius/pen/QWBLOJZ

Can someone help me?


Solution

  • When using vue, the variables must be reactive to make changes on data. It's also accessible on .value. Read more on this https://vuejs.org/guide/essentials/reactivity-fundamentals.html and accessing the refs https://vuejs.org/guide/essentials/template-refs.html#accessing-the-refs

    Here's a sample working code

    <template>
      <ul v-for="number in numbers">
        <li>{{ number.num }} : {{ number.text }}</li>
      </ul>
      {{ numbers }}
    </template>
    
    <script setup>
    import { ref } from 'vue'
    let numbers = ref([
      { num: 1, text: "One" },
      { num: 2, text: "Two" },
      { num: 3, text: "Three" }
    ]);
    
    // simulate server
    setTimeout(() => {
      numbers.value.push({ num: 4, text: "Four" });
      console.log(numbers); // returns the array correct
    }, 3000);
    </script>