【问题标题】:SvelteJS: Dynamically add N components, where N is the integer value of an input elementSvelteJS:动态添加 N 个组件,其中 N 是输入元素的整数值
【发布时间】:2019-02-20 12:56:28
【问题描述】:

使用 SvelteJS v2.16.1。 尝试动态添加 N 个组件,其中 N 是在输入元素中输入的值。 以下是它现在的大致样子:

<input min="1" type="number" bind:value="quantity"/>
<script>
export default {
  data() {
    return {
      quantity: 1
    }
  }
}
</script>

我想在 {#each} 之类的东西中使用 {quantity} 来动态创建新元素。 有点像这样:

<input min="1" type="number" bind:value="quantity"/>
{#each quantity as i}
  <input type="text />
{/each}

但是 {quantity} 是一个整数值,所以我不能在 {#each} 中使用它。

关于如何处理此问题的任何建议?

【问题讨论】:

    标签: svelte


    【解决方案1】:

    each 块的值应该是一个数组(或类似数组的对象,即它有一个length 属性)。所以你可以这样做Array(quantity),像这样:

    <input min="1" type="number" bind:value="quantity"/>
    {#each Array(quantity) as i}
      <input type="text">
    {/each}
    

    REPL demo.

    【讨论】:

    • 非常好。感谢您的及时回复。
    猜你喜欢
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    相关资源
    最近更新 更多