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的强大核心是 响应式 的保持Dom和应用状态一致, 例如: 事件响应

At the heart of Svelte is a powerful system of reactivity for keeping the DOM in sync with your application state — for example, in response to an event.

接下来是个计数器的例子。可以通过使用$state(...)count变成响应式的。

Make the count declaration reactive by wrapping the value with $state(...):

App
let count = $state(0);

在Svelte中称这个$staterune (符文),用来告诉Svelte count 可不是一个普通的变量。符文虽然看起来用起来都有点像函数,但是他们其实是语言的一部分。

This is called a rune, and it’s how you tell Svelte that count isn’t an ordinary variable. Runes look like functions, but they’re not — when you use Svelte, they’re part of the language itself.

接下来需要做的就是实现 递增

All that’s left is to implement increment:

App
function increment() {
	count += 1;
}

$state rune是不是跟React的useState类似

Edit this page on GitHub

1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
	let count = 0;
 
	function increment() {
		// TODO implement
	}
</script>
 
<button onclick={increment}>
	Clicked {count}
	{count === 1 ? 'time' : 'times'}
</button>