Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
Transitions
Advanced Svelte
Advanced reactivity
Reusing content
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

在Svelte中,应用是有一个或多个 组件 组成的. 组件是写在 .svelte 文件里可以重用自包含的封装了相应HTML, CSS和JavaScript的代码块。 当前在编辑器中打开的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

一个只是显示些静态标签的组件好像少点意思,我们来给它添加点数据

A component that just renders some static markup isn’t very interesting. Let’s add some data.

首先,在组件里添加一对script标签并在里面定义个变量name:

First, add a script tag to your component and declare a name variable:

App
<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:

App
<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.

App
<h1>Hello {name.toUpperCase()}!</h1>

Edit this page on GitHub

1
2
<h1>Hello world!</h1>