如何安装svelte
One great thing about Svelte is that you don’t need to do anything special to update the state of a component.
Svelte的一大优点是您无需执行任何特殊操作即可更新组件的状态。
All you need is an assignment.
您所需要做的只是一项任务。
Say you have a count
variable. You can increment that using, simply, count = count + 1
, or count++
:
假设您有一个count
变量。 您可以简单地使用count = count + 1
或count++
来增加它:
<script>
let count = 0
const incrementCount = () => {
count++
}
</script>
{count} <button on:click={incrementCount}>+1</button>
This is nothing groundbreaking if you are unfamiliar with how modern Web frameworks handle state, but in React you’d have to either call this.setState()
, or use the useState()
hook.
如果您不熟悉现代Web框架如何处理状态,那么这并不是开创性的,但是在React中,您必须调用this.setState()
或使用useState()
挂钩。
Vue takes a more structured approach using classes and the data
property.
Vue使用类和data
属性采用了更结构化的方法。
Having used both, I find Svelte to be a much more JavaScript-like syntax.
两者都使用过后,我发现Svelte是一种更像JavaScript的语法。
We need to be aware of one thing, which is learned pretty quickly: we must also do an assignment when changing the value.
我们需要注意一件事,这很快就会学到:更改值时还必须进行赋值。
For simple values like strings and numbers, that’s mostly a given, because all methods on String return new strings, and same for numbers - they are immutable.
对于诸如字符串和数字之类的简单值,这通常是给定的,因为String上的所有方法都返回新的字符串,数字也一样,它们都是不可变的。
But for arrays? We can’t use methods that alter the array. Like push()
, pop()
, shift()
, splice()
… because there’s no assignment. They change the inner data structure, but Svelte can’t detect that.
但是对于数组? 我们不能使用改变数组的方法。 像push()
, pop()
, shift()
, splice()
,因为没有分配。 他们更改了内部数据结构,但Svelte无法检测到。
Well, you can still use them, but after you’ve done your operation, you reassign the variable to itself, like this:
好的,您仍然可以使用它们,但是在完成操作之后,您可以将变量重新分配给它自己,如下所示:
let list = [1, 2, 3]
list.push(4)
list = list
Which is a bit counter-intuitive, but you’ll quickly remember it.
这有点违反直觉,但是您会很快记住它。
Or you can use use the spread operator to perform operations:
或者,您可以使用传播操作符执行操作:
let list = [1, 2, 3]
list = [...list, 4]
如何安装svelte