【问题标题】:The v-for range expect an integer value but got NaNv-for 范围期望一个整数值但得到 NaN
【发布时间】:2021-11-11 14:53:51
【问题描述】:

v-for 指令无法读取 nStars 属性来执行循环。看,我正在尝试使用组件<display-stars> 来显示多颗星。但由于某种原因,组件没有接收到 nStars 属性来执行循环。这是我的代码:
HTML

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

逻辑

  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");

我尝试阅读有关 how to pass propshow to use v-for using an integer instead of a collection 的 vue 文档。我可能忘记了一些事情,因为我真的是 Vue 3 的新手,但是来自 react 背景。

【问题讨论】:

  • 我认为问题出在您的 keyIndex 上。试试v-for="(i, index) in nStars" :key="index"

标签: javascript vue.js vuejs3


【解决方案1】:

nStarsNumber。你可以使用v-foronly with arrays or objects

要创建一个包含 3 个元素的 Array,您可以使用 Array.from

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

这将创建[undefined, undefined, undefined]。 (您也可以创建包含未定义元素的数组。请参阅MDN。)

所以要在 Vue 中循环 nStars 次:

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

其中i 是索引。

【讨论】:

    【解决方案2】:

    您是否尝试过使用索引:

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

    【讨论】:

    • 我仍然遇到同样的错误。
    猜你喜欢
    • 2022-12-12
    • 2014-09-01
    • 1970-01-01
    • 2021-11-26
    • 2022-12-05
    • 2012-11-10
    • 2010-11-06
    • 2020-03-03
    • 2023-03-03
    相关资源
    最近更新 更多