[英]Reactive variables are not working - svelte
Reactive variables are not working in my svelte application.反应变量在我的苗条应用程序中不起作用。 When I log them on my console they are
undefined
.当我在控制台上记录它们时,它们是
undefined
。
I have in App.svelte
the following relevant code我在
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}/>
In PollsList.svelte
I have the following relevant code在
PollsList.svelte
我有以下相关代码
<script>
export let polls = [];
</script>
{#each polls as poll (poll.id)}
<PollItem {poll} on:vote/>
{/each}
and in my PollItem.svelte
I have the following relevant code在我的
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>
The console.log
in the last code gives undefined, undefined, undefined, 16, 4
, which means although poll.votesA
and poll.votesB
reach the component, the reactive variables are undefined
.最后一个代码中的
console.log
给出了undefined, undefined, undefined, 16, 4
,这意味着虽然poll.votesA
和poll.votesB
到达了组件,但反应变量是undefined
。 Why is that?这是为什么? What did I do wrong?
我做错了什么?
In your case the variables are not done evaluated yet to log them and the way to fix that is be usning console.log reactively like the following:在您的情况下,尚未对变量进行评估以记录它们,而解决该问题的方法是反应性地使用 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);
or make it all inside a block:或将其全部放在一个块内:
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.