Svelte - 每个循环中的重要中间变量
我怎样才能像在 React 中一样在 Svelte 的 HTML 中创建变量,或者这根本不是我应该如何使用 Svelte 的方式。我知道下面的例子很简单,但我正在考虑一种情况,我确实需要一些复杂的逻辑 subArray
(无法使用单行)
React
<ul>
{myArray.map((item) => {
const subArray = item.items.filter(i = i > 0) // <- how can I have an intermediate variable like this in Svelte?
return <li>{subArray.map(...)}</li>
}}
</ul>
苗条
<ul>
{#each myArray as item}
<li>
{#each <complex-logic> as subItem}
...
{/each}
</li>
{/each}
</ul>
How can I create variables inside Svelte's HTML like in React, or is it not at all how I am supposed to use Svelte. I know the example below is trivial but I'm thinking of a case where I really need some heavy logic for subArray
(could not use a one liner)
React
<ul>
{myArray.map((item) => {
const subArray = item.items.filter(i = i > 0) // <- how can I have an intermediate variable like this in Svelte?
return <li>{subArray.map(...)}</li>
}}
</ul>
Svelte
<ul>
{#each myArray as item}
<li>
{#each <complex-logic> as subItem}
...
{/each}
</li>
{/each}
</ul>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
{@const}
指令,该指令是Svelte 最近添加的内容。在您的用例中:You can use the
{@const}
directive, which is a recent addition to Svelte. In your use case:如果不是太复杂,您可以直接修改
{#each}
中的数组,或者可以使用新的
{@const}
指令如果它更复杂,为什么不将逻辑提取到函数中
这是一个 REPL 包含所有选项
If it's not too complicated you can directly modify the array inside
{#each}
or you could use the new
{@const}
directiveAnd if it's even more complicated, why not extract the logic into a function
Here's a REPL with all the options