简体   繁体   中英

Getting an updated array to update in a Vue3 template

While this is not the exact code, it represents the issue. I have an object that has a method that returns an array. This array is then updated asynchronously. In the demo it is a timeout but in reality it would be an HTTP call:

function () {
 let a = ['apple'];

 setTimeout(() => {
   a.push['banana'];
 }, 3000);

 return a;
}

Then it is included in a Vue component via a computed property and displayed, eg

   <ul>
      <li v-for="(row, index) in testObjectArr" v-bind:key="index">
         {{row}}
      </li>
   </ul>

However this only displays the first entry (apple) and not the second (banana). If an event does cause the template to refresh then it does appear. Using things like watch also doesn't work. The only way to get it working is to pass a handler in to the object that manually triggers a redraw which is oviously less than ideal. Is there any way to get responsivity to actually work with the above situation?

In order to make variables reactive, you should declare them as such by using ref or reactive . So your code should be:

<script setup>
import { ref } from 'vue';

const items = ref(['apple']);

setTimeout(() => {
  items.value.push('banana');
}, 1000);
</script>

<template>
  <ul>
    <li v-for="(item, index) of items" :key="index">
      {{ item }}
    </li>
  </ul>
</template>

See it live

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM