0

我在 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}.

我怎样才能得到想要的结果?

4

1 回答 1

3

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

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

这是文档链接

于 2020-06-27T12:03:12.930 回答