片段允许你在组件内重复使用内容,而无需将其提取到单独的文件中。
¥Snippets allow you to reuse content within a component, without extracting it out into a separate file.
在这个练习中,我们将创建 三种明智之举猴子 的表格,以及它们的 unicode 转义序列和 HTML 实体。到目前为止,我们只有一只猴子。
¥In this exercise, we’re creating a table of the three wise monkeys, along with their unicode escape sequences and HTML entities. So far, we have but a single monkey.
当然,我们可以复制标记。或者我们可以创建一个 { emoji, description }
对象数组并将其传递给 {#each ...}
块。但更简洁的解决方案是将标记封装在可重用的块中。
¥We could duplicate the markup, of course. Or we could create an array of { emoji, description }
objects and pass it into an {#each ...}
block. But a neater solution is to encapsulate the markup in a reusable block.
首先声明一个代码片段:
¥Begin by declaring a snippet:
{#snippet monkey()}
<tr>
<td>{emoji}</td>
<td>{description}</td>
<td>\u{emoji.charCodeAt(0).toString(16)}\u{emoji.charCodeAt(1).toString(16)}</td>
<td>&#{emoji.codePointAt(0)}</td>
</tr>
{/snippet}
在我们渲染它之前,猴子不再可见。让我们这么做:
¥The monkey is no longer visible until we render it. Let’s do that:
<tbody>
{#snippet monkey()}...{/snippet}
{@render monkey()}
</tbody>
在我们将代码片段用于其余的 monkeys 之前,我们需要将数据传递到代码片段中。片段可以有零个或多个参数:
¥Before we can use the snippet for the rest of our monkeys, we need to pass data into the snippet. Snippets can have zero or more parameters:
<tbody>
{#snippet monkey(emoji, description)}...{/snippet}
{@render monkey('🙈', 'see no evil')}
</tbody>
如果你愿意,你还可以使用解构参数。
¥[!NOTE] You can also use destructured parameters, if you like.
添加其余的猴子:
¥Add the rest of the monkeys:
'🙈', 'see no evil'
'🙉', 'hear no evil'
'🙊', 'speak no evil'
最后,删除我们不再需要的 <script>
块:
¥Finally, delete the <script>
block we no longer need it:
<script>
let emoji = '🙈';
let description = 'see no evil';
</script>
<script lang="ts">
let emoji = '🙈';
let description = 'see no evil';
</script>
代码片段可以在组件中的任何位置声明,但与函数一样,仅在同一个 ‘scope’ 或子作用域中渲染标签时可见。
¥[!NOTE] Snippets can be declared anywhere in your component, but, like functions, are only visible to render tags in the same ‘scope’ or a child scope.
<script>
let emoji = '🙈';
let description = 'see no evil';
</script>
<table>
<thead>
<tr>
<th>emoji</th>
<th>description</th>
<th>unicode escape sequence</th>
<th>html entity</th>
</tr>
</thead>
<tbody>
<tr>
<td>{emoji}</td>
<td>{description}</td>
<td>\u{emoji.charCodeAt(0).toString(16)}\u{emoji.charCodeAt(1).toString(16)}</td>
<td>&#{emoji.codePointAt(0)}</td>
</tr>
</tbody>
</table>
<style>
th, td {
padding: 0.5em;
}
td:nth-child(3),
td:nth-child(4) {
font-family: monospace;
}
</style>