簡體   English   中英

顯示帶有 Svelte 和 Strapi v4 的 object 的屬性

[英]Showing attributes of an object with Svelte and Strapi v4

我正在為一個項目使用 Strapi v4 和 Svelte(我在開發方面也很新,抱歉,我的問題可能是基本的)。 我從本地主機獲取我的 Strapi 數據並將它們放入控制台日志,沒問題。 使用 GraphQL,我得到如下數據,例如:

"produits": {
  "data": [
    {
      "id": "1",
      "attributes": {
        "reference": "MEV620001"
      }
    }

我的問題是用 Svelte 渲染它們時,我只能獲取 ID,不知道如何顯示每個產品的屬性。 使用 Strapi v3,我可以,但我現在無法更改使用 Strapi v4 顯示數據的方式。 我在 Svelte 中的代碼是:

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

let produits = []

onMount(async () => {
    const response  = await fetch('http://localhost:1337/api/produits')
    produits = await response.json()
    console.log(produits)
})

</script>

{#if produits.data}
{#each produits.data as produit}
<h3>{produit.id}{produit.reference}</h3>  ///how to enter into the attributes with Strapi v4 ?///
<hr />
{:else}
<p>Chargement...</p>
{/each}
{/if}

使用上面的代碼,我在前端得到了未定義的“引用”,這是因為“引用”在這個特定 id 的屬性內部,我不知道如何進入屬性內部來渲染它們。 非常感謝您的大力幫助。

您需要訪問attributes然后reference這可以使用produit.attributes.reference在您的代碼中完成

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

  let produits = [];

  onMount(async () => {
    const response = await fetch("http://localhost:1337/api/produits");
    produits = await response.json();
    console.log(produits);
  });
</script>

{#if produits.data}
  {#each produits.data as produit}
    <h3>{produit.id}{produit.attributes.reference}</h3> <!-- modified this line -->
    ///how to enter into the attributes with Strapi v4 ?///
    <hr />
  {:else}
    <p>Chargement...</p>
  {/each}
{/if}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM