Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading