如何在 svelte 中使用函数 return 值

How to use function return value in svelte

我正在尝试将函数的返回值获取到 svelte 组件中。 但是,我的函数是这样构造的:

GetData.svelte

<script>

  import { Modal, Button, Card } from "svelte-chota";


  let modal_open = false;
  let recordsObject = {};
  let records = [];
  
  const apiURL =
    "...src/Data/data.json";

  // Fetch data from the API
  async function getDataFromApi() {
    const response = await fetch(apiURL);
    recordsObject = await response.json();
    records = recordsObject.records;

    // Server responses is OK then
    if (response.status === 200) {
      console.log("Success");
    } else {
      // Otherwise check the error
      throw new Error(response.status);
    }

    // Stats Functions
    // Count total records
    function countTotalRecords(totalRecord) {
      totalRecord = console.log(records.length);
      return totalRecord;
    }
    countTotalRecords();
}

</script>

<!-- Button to display stats -->
<Button on:click={(event) => (modal_open = true)}><pre> Stats</pre></Button>
<Modal bind:open={modal_open}>
  <Card>
    <div>
      <b><p>Below you will find the list of stats:</p></b>
      **<p>Total Records: {totalRecord}</p>**
      <p>Count of different event types:</p>
      <p>Min delay between intereactions:</p>
      <p>Max delay between intereactions:</p>
      <p>Mean delay between intereactions:</p>
      <p>Length of the longest sequence ("Topics filtered"):</p>
      <p>Total Time of All interactions:</p>
    </div>
  </Card>
</Modal>
    

问题出在这部分:

<p>Total Records: {totalRecord}</p>

错误:'totalRecord' 未定义 svelte(缺少声明)

我想实现的是当我点击模型“Stats”时,模型会出现并且必须显示值 {totalRecord}。

拜托,有人能帮我解决这个问题吗? 通过在互联网上搜索。我读过我需要导出变量或使用绑定或存储...老实说,我对如何实现这一点感到有些困惑。 谢谢

如评论中所述,您需要声明一个变量才能在模板中使用它。然后,当值可用时,您可以更新该变量。最初您的模板将显示零,然后当数据加载时它将更改为正确的值。

  import { Modal, Button, Card } from "svelte-chota";


  let modal_open = false;
  let recordsObject = {};
  let records = [];
  // variables declared here should be available in your templates, hopefully
  let totalRecord = 0;
  
  const apiURL =
    "...src/Data/data.json";

  // Fetch data from the API
  async function getDataFromApi() {
    const response = await fetch(apiURL);
    // Server responses is OK then
    if (response.status === 200) {
      console.log("Success");
    } else {
      // Otherwise check the error
      throw new Error(response.status);
    }
    // do this after you know response.status is ok
    recordsObject = await response.json();
    records = recordsObject.records;
    // set the above variable to the right value
    totalRecord = records.length;
  }