【问题标题】:While hooping an array of objects in Svelte, how can I display the iteration count?在 Svelte 中连接一组对象时,如何显示迭代计数?
【发布时间】:2020-06-27 23:55:46
【问题描述】:

我正在 Svelte 的 onMount 方法的帮助下迭代 JSON。我已经在表格中显示了数据。

<script>
    import { onMount } from "svelte";

    const apiURL = "https://gist.githubusercontent.com/Goles/3196253/raw/9ca4e7e62ea5ad935bb3580dc0a07d9df033b451/CountryCodes.json";        
    let countries = [];
    
    onMount(async function() {
       const response = await fetch(apiURL);
       countries = await response.json();
    });

</script>

<table class="table table-bordered">
  <thead>
    <tr>
      <th>#</th>
      <th>Name</th>
      <th>Code</th>
    </tr>
  </thead>
  <tbody>
    {#if countries}
     {#each countries as country }  
     <tr>
      <td>{index + 1}</td>
      <td>{country.name}</td>
      <td>{country.code}</td>
     </tr>
     {/each}
    {:else}
    <p>There are no countries</p>
    {/if}
  </tbody>
</table>

我无法做的是添加一个迭代计数列。使用{index + 1}

如何获得想要的结果?

【问题讨论】:

    标签: javascript svelte svelte-3 svelte-2


    【解决方案1】:

    索引是 svelte 中 each 循环的第二个参数

    {#each countries as country, index }  
      <tr>
      <td>{index + 1}</td>
      <td>{country.name}</td>
      <td>{country.code}</td>
      </tr>
    {/each}
    

    这里是docs link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-25
      • 2022-10-12
      相关资源
      最近更新 更多