[英]Svelte: How to pass data or props from a child component to the parent?
[英]Svelte - how to wait for data that is being passed in from parent component?
我正在學習 Svelte,我想在三個組件中使用來自一個 JSON API 的數據。 數據如下所示:
{
"stats": {
"currentYear": {
"total": 6,
"success": 6
},
"thirty": {
"total": 30,
"success": 28
},
"hundred": {
"total": 100,
"success": 92
},
"allTime": {
"total": 789,
"success": 728
}
},
"heatmap": {
...
},
"other": {
...
}
}
我通過異步獲取通過onMount
主組件中的App.svelte
檢索數據,這很好用。 然后我想將每個 object 傳遞給其對應的組件,因此stats
object 傳遞給Stats.svelte
, heatmap
object 傳遞給Heatmap.svelte
等。
為了說明我的問題,在Stats.svelte
我試圖顯示每個時間段的百分比值,例如:
此外,每個 CSS class 將基於一些閾值來更改顏色(x >= 95:綠色,95 > x >= 90:黃色,x < 90:紅色)。
所以需要一些基本的計算,我想在通用 function 中進行,如下所示。
stats
object 確實是從父組件App.svelte
的,如果我只想通過{#await}
塊在 HTML 中顯示它的值,這將正常工作。 但是,我想做一些計算,所以我想調用一個 function 來使用stats
對象的數據,但我不知道如何在適當的時候調用這個 function。 在onMount
上調用是不行的,因為太早了,還沒有收到從父組件進來的數據。
<script>
import { onMount } from "svelte"
export let stats
let currentYearClass, currentYearStat
const calcPercentage = async (period) => {
currentYearStat = stats[period].currentYearSuccess * 100 / stats[period].currentYearTotal
currentYearClass = 'green'
}
onMount( async () => {
calcPercentage('currentYear')
})
</script>
<div id="stats">
{#await stats}
<div>Waiting for stats ...</div>
{:then stats}
<div class="{currentYearClass}" id="currentYear">{currentYearStat}</div>
...
...
{/await}
</div>
有幾種方法可以做到這一點,但一種方法是讓calcPercentage
將stats
作為參數,然后反應性地調用它。
export let stats
let currentYearClass, currentYearStat
const calcPercentage = (stats, period) => {
currentYearStat = stats[persion}......
currentYearClass = 'green'
}
$: stats && calcPercentage(stats, 'currentYear')
編輯:一些解釋
原始解決方案的第一個問題,您可能注意到的一點是,在沒有正確數據的情況下安裝了組件,導致未定義統計信息。
上述解決方案分兩步進行:
$: stats && calcPercentage(stats, 'currentYear')
第一部分定義了一個反應性語句,它將檢查stats的計算結果是否為 true,除非它未定義、false 或 0,否則它將執行某些操作。如果stats為 true,它將執行 function。
第二部分與之前的 function 相同,我在此處添加了stats參數,盡管在這種情況下嚴格不需要它,因為 function 將,因為之前執行每次stats更改並且是一個類似於 true 的值。
有了這兩個,當掛載反應性語句時,由於stats未定義,function 不會執行。 一旦數據進入,它將被重新評估, stats不再是未定義的,並且 function 會觸發。
額外的
當反應性語句采用以下形式時:
$: myfunction(myvar)
它會在 myvar 的每個值更改時執行,即使在掛載期間也是如此(考慮它從不存在變為未定義?)。 這意味着您必須將檢查移至 function 本身,對於某些情況,這可能是需要的,例如,這實際上是分配的一部分,而 function 本身是在組件外部定義的
import heavyCalc from 'heavy/calc/function`
$: value = heavyCalc(otherValue)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.