在 Svelte 中,应用由一个或多个组件组成。组件是一个可重复使用的自包含代码块,它封装了 HTML、CSS 和 JavaScript,它们一起写入 .svelte
文件。在右侧的代码编辑器中打开的 App.svelte
文件是一个简单的组件。
¥In Svelte, an application is composed from one or more components. A component is a reusable self-contained block of code that encapsulates HTML, CSS and JavaScript that belong together, written into a .svelte
file. The App.svelte
file, open in the code editor to the right, is a simple component.
添加数据(Adding data)
¥Adding data
仅渲染一些静态标记的组件并不是很有趣。让我们添加一些数据。
¥A component that just renders some static markup isn’t very interesting. Let’s add some data.
首先,向你的组件添加一个脚本标签并声明一个 name
变量:
¥First, add a script tag to your component and declare a name
variable:
<script>
let name = 'Svelte';
</script>
<h1>Hello world!</h1>
<script lang="ts">
let name = 'Svelte';
</script>
<h1>Hello world!</h1>
然后,我们可以在标记中引用 name
:
¥Then, we can refer to name
in the markup:
<h1>Hello {name}!</h1>
在大括号内,我们可以放置任何我们想要的 JavaScript。尝试将 name
更改为 name.toUpperCase()
,以获得更响亮的问候。
¥Inside the curly braces, we can put any JavaScript we want. Try changing name
to name.toUpperCase()
for a shoutier greeting.
<h1>Hello {name.toUpperCase()}!</h1>
<h1>Hello world!</h1>