[英]Reactive variables are not working - svelte
反應變量在我的苗條應用程序中不起作用。 當我在控制台上記錄它們時,它們是undefined
。
我在App.svelte
中有以下相關代碼
<script>
let polls = [
{
question: "JavaScript or Python?",
answerA: "JavaScript",
answerB: "Python",
votesA: 16,
votesB: 4
}
]
const handleVote = e => {/* increase vote A or vote B by 1*/}
</script>
<PollsList {polls} on:vote={handleVote}/>
在PollsList.svelte
我有以下相關代碼
<script>
export let polls = [];
</script>
{#each polls as poll (poll.id)}
<PollItem {poll} on:vote/>
{/each}
在我的PollItem.svelte
我有以下相關代碼
<script>
import {createEventDispatcher} from "svelte";
const disptach = createEventDispatcher();
export let poll;
$: totalVotes = poll.votesA + poll.votesB;
$: percentA = Math.round(poll.votesA / totalVotes) * 100;
$: percentB = Math.round(poll.votesB / totalVotes) * 100;
console.log(totalVotes, percentA, percentB, poll.votesA, poll.votesB);
const handleVote = (option, id) => dispatch("vote", {option, id});
</script>
<div>
<div class = "answer" on:click={() => handleVote("a", poll.id)}{poll.answerA}</div>
<div class = "answer" on:click={() => handleVote("b", poll.id)}{poll.answerB}</div>
</div>
最后一個代碼中的console.log
給出了undefined, undefined, undefined, 16, 4
,這意味着雖然poll.votesA
和poll.votesB
到達了組件,但反應變量是undefined
。 這是為什么? 我做錯了什么?
在您的情況下,尚未對變量進行評估以記錄它們,而解決該問題的方法是反應性地使用 console.log,如下所示:
$: totalVotes = poll.votesA + poll.votesB;
$: percentA = Math.round(poll.votesA / totalVotes) * 100;
$: percentB = Math.round(poll.votesB / totalVotes) * 100;
$: console.log(totalVotes, percentA, percentB, poll.votesA, poll.votesB);
或將其全部放在一個塊內:
let totalVotes, percentA, percentB;
$:{
totalVotes = poll.votesA + poll.votesB;
percentA = Math.round(poll.votesA / totalVotes) * 100;
percentB = Math.round(poll.votesB / totalVotes) * 100;
console.log(totalVotes, percentA, percentB, poll.votesA, poll.votesB);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.