Svelte中的反应性陈述

如何在Svelte中使用反应式语句

在Svelte中,您可以侦听组件状态的变化,并更新其他变量。

例如,如果您有一个count多变的:

<script>
let count = 0
</script>

然后您通过单击按钮对其进行更新:

<script>
let count = 0

const incrementCount = () => { count = count + 1 } </script>

{count} <button on:click={incrementCount}>+1</button>

您可以听有关的更改count使用特殊语法$:它定义了一个新块,当其中引用的任何变量发生更改时,Svelte都会重新运行。

这是一个例子:

<script>
let count = 0

const incrementCount = () => { count = count + 1 }

$: console.log(</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">count</span><span style="color:#e6db74">}</span><span style="color:#e6db74">) </script>

{count} <button on:click={incrementCount}>+1</button>

我用了块:

$: console.log(`${count}`)

您可以编写其中一个以上的代码:

<script>
$: console.log(`the count is ${count}`)
$: console.log(`double the count is ${count * 2}`)
</script>

您还可以添加一个块来组合多个语句:

<script>
$: {
  console.log(`the count is ${count}`)
  console.log(`double the count is ${count * 2}`)
}
</script>

我在那里使用了console.log()调用,但是您也可以更新其他变量:

<script>
let count = 0
let double = 0

$: { console.log(the count is </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">count</span><span style="color:#e6db74">}</span><span style="color:#e6db74">) double = count * 2 console.log(double the count is </span><span style="color:#e6db74">${</span><span style="color:#66d9ef">double</span><span style="color:#e6db74">}</span><span style="color:#e6db74">) } </script>

免费下载我的苗条手册


更多精妙的教程: