Home > Blockchain >  The v-for range expect an integer value but got NaN
The v-for range expect an integer value but got NaN

Time:09-17

v-for directive is unable to read nStars prop to execute loop. Look I'm trying to display multiple stars by using the component <display-stars>. But for some reason the component is not receiving the nStars prop to execute loop. This is my code:
HTML

<h1><display-stars :nStars="3"></display-stars></h1>

Logic

  const app = Vue.createApp({}); // It contains more logic, but it's not relevant.
  app.component("star", { template: `<i class="fas fa-star"></i>` });
  app.component("empty-star", { template: `<i class="far fa-star"></i>` });
  app.component("display-stars", {
    props: ["nStars"],
    template: `<div class="stars-container">
     <star v-for="i in nStars" :key="i"></star> <empty-star v-for="j in (5-nStars)" :key="j"></empty-star>
    </div>`,
  });

  const componentInstance_vm = app.mount("#app");

I tried reading the vue docs about how to pass props, and how to use v-for using an integer instead of a collection. I might forgot something since I'm really new to Vue 3, but come from a react background.

CodePudding user response:

Did you try with index:

<star v-for="(i, index) in nStars" :key="index"></star>

CodePudding user response:

nStars is a Number. You can use v-for only with arrays or objects.

To create an Array of 3 elements you can use Array.from :

let arr = Array.from({length: 3});

which will create [undefined, undefined, undefined]. (You can create arrays with non-undefined elements too. Refer MDN.)

So to loop nStars times in Vue do :

<star v-for="(o,i) in Array.from({length: nStars})" :key="i"></star>

where i is the index.

  • Related