Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
加载数据
Headers和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>