苗条的生成树_苗条手册

苗条的生成树

I wrote this book to help you quickly learn Svelte and get familiar with how it works.

我写这本书是为了帮助您快速学习Svelte并熟悉它的工作原理。

The ideal reader of the book has zero knowledge of Svelte, has maybe used Vue or React, but is looking for something more, or a new approach to things.

本书的理想读者对Svelte知识为零,可能使用过Vue或React,但是正在寻找更多 东西 ,或者寻找一种新的方法。

I find that Svelte is very much worth looking into, because it provides a refreshing point of view and several unique features to the Web.

我发现Svelte非常值得研究,因为它提供了令人耳目一新的观点和Web的一些独特功能。

Thank you for getting this ebook. I hope it will help you learn more about Svelte!

感谢您获得此电子书。 希望它能帮助您了解有关Svelte的更多信息!

Note: you can download a PDF / ePub / Mobi version of this book so you can read it offline.

注意:您可以下载本书的PDF / ePub / Mobi版本,以便离线阅读。

You can reach me on Twitter @flaviocopes.

您可以通过Twitter @flaviocopes与联系

My website is flaviocopes.com.

我的网站是flaviocopes.com

图书索引 (Book Index)

Card.svelte介绍 (Introduction to Svelte)

Svelte is an exciting Web framework that offers a fresh new take on how to build Web applications.

Svelte是一个令人兴奋的Web框架,它为如何构建Web应用程序提供了新的思路。

If you are already experienced in React, Vue, Angular or other frontend frameworks you might be pleasantly surprised by Svelte.

如果您已经对React,Vue,Angular或其他前端框架有所了解,那么Svelte可能会让您感到惊喜。

My first impression with Svelte was that it all feels so much more like plain JavaScript than working with other frameworks. Sure, you have some rules and there are templates that are not 100% JavaScript (they look more like HTML). But most of the things that are complicated with other frameworks are very simple and lightweight with Svelte.

我对Svelte的第一印象是,与使用其他框架相比,它看上去更像纯JavaScript。 当然,您有一些规则,并且有一些模板不是100%JavaScript(它们看起来更像HTML)。 但是,使用其他框架,大多数复杂的事情对于Svelte来说都是非常简单和轻量级的。

And my first impression has been confirmed by further usage of the framework and its ecosystem of tools.

框架及其工具生态系统的进一步使用证实了我的第一印象。

Compared to React, Vue, Angular and other frameworks, an app built using Svelte is compiled beforehand so you don't have to serve the whole framework to every one of your site visitors. As a result, the fruition of the experience is smoother, consumes less bandwidth, and everything feels faster and more lightweight.

与React,Vue,Angular和其他框架相比,使用Svelte构建的应用程序是预先编译的,因此您不必为每个网站访问者都提供整个框架。 结果,体验的结果更加流畅,消耗的带宽更少,一切感觉都更快,更轻便。

At deployment, Svelte disappears and all you get is plain (and fast!) JavaScript.

在部署时,Svelte消失了,您得到的只是普通的(而且很快!)JavaScript。

如何开始使用Svelte (How to get started with Svelte)

To use Svelte, you need to have Node.js installed because all the tooling we're going to use is based on Node. Check out my tutorial how to install Node.js if you don't have it already!

要使用Svelte,您需要安装Node.js,因为我们将使用的所有工具都基于Node。 如果没有的话,请查看我的教程如何安装Node.js

And make sure it's the latest version (how to update Node.js).

并确保它是最新版本( 如何更新Node.js )。

If you don't want to install Node, the Svelte website provides a very cool REPL (Read-Eval-Print Loop) at https://svelte.dev/repl. It's handy to test small Svelte apps and to experiment with things.

如果您不想安装Node,则Svelte网站在https://svelte.dev/repl上提供了一个非常酷的REPL(读-评估-打印循环)。 测试小型Svelte应用程序并进行实验非常方便。

Node installs the npx command, which is a handy way to run Node commands. In particular, we're going to run this:

Node安装npx命令,这是运行Node命令的便捷方法。 特别是,我们将运行以下代码:

npx degit sveltejs/template firstapp

This will download and run the degit command, which in turn downloads the latest code of the Svelte project template living at https://github.com/sveltejs/template, into a newly created firstapp folder.

这将下载并运行degit命令 ,该命令又将位于https://github.com/sveltejs/template的Svelte项目模板的最新代码下载到新创建的firstapp文件夹中。

Make sure that git is installed on your machine and added to the PATH variable, otherwise the degit command won't work. In case things are still not working out for you, you can alternatively 'Clone or download' the template project and then delete the hidden .git folder. This is basically the same thing that the degit command does (only difference is that the folder is called template instead of firstapp).

确保git已安装在您的计算机上并添加到PATH变量中,否则degit命令将不起作用。 如果仍然无法解决问题,您可以选择“克隆或下载”模板项目,然后删除隐藏的.git文件夹。 这基本上与degit命令执行的操作相同(唯一的不同是,该文件夹称为template而不是firstapp )。

Now go into that firstapp folder and run npm install to download the additional dependencies of the template. At the time of writing, these are the dependencies of that project template:

现在进入该firstapp文件夹并运行npm install以下载模板的其他依赖项。 在撰写本文时,这些是该项目模板的依赖项:

"npm-run-all"
"rollup"
"rollup-plugin-commonjs"
"rollup-plugin-livereload"
"rollup-plugin-node-resolve"
"rollup-plugin-svelte"
"rollup-plugin-terser"
"svelte"

As you can see, it's the Svelte core, plus Rollup (a Webpack alternative) and some of its plugins. Plus npm-run-all, a CLI tool that is used to run multiple npm scripts in parallel or sequential.

如您所见,它是Svelte核心,再加上Rollup (一种Webpack替代品)及其一些插件。 加上npm-run-all ,这是一个CLI工具,用于并行或顺序运行多个npm脚本。

We're now ready to run our Svelte site in development mode, by running

现在,我们可以通过运行以下命令以开发模式运行Svelte网站

npm run dev

This will start the app on localhost, on port 5000, by default:

默认情况下,这将在本地主机上的端口5000上启动应用程序:

If you point your browser there, you'll see the "Hello world!" example:

如果将浏览器指向那里,您将看到“ Hello world!” 例:

You're now ready to open the code in your favorite editor. The src folder contains all you need to tweak the app: the main.js file:

现在您可以在自己喜欢的编辑器中打开代码了。 src文件夹包含调整应用程序所需的全部: main.js文件:

This file is the entry point and in this case initializes the App component, which is defined in App.svelte, a single file component:

该文件是入口点,在这种情况下,将初始化App组件,该组件在App.svelte定义,单个文件组件为:

<script>
export let name;
</script>

<style>
h1 {
color: purple;
}
</style>

<h1>Hello {name}!</h1>

苗条的组件 (Svelte components)

Modern Web development is very much focused on components, and Svelte is no different.

现代Web开发非常关注组件,而Svelte也不例外。

What is a component? A component is an atomic part of the application that is self-contained and optionally references other components to compose its output.

什么是成分? 组件是应用程序的原子部分,它是独立的,可以选择引用其他组件来构成其输出。

In other words, it's a compartmentalized part of the application. A form can be a component. An input element can be a component. The whole application is a component.

换句话说,它是应用程序的一部分。 表单可以是组件。 输入元素可以是组件。 整个应用程序是一个组件。

Svelte components contain all that's needed to render a piece of the UI. Every Svelte component is declared in a .svelte file, and in there you'll find the content (markup), the behavior (JavaScript), and the presentation (CSS) without having to define separate files.

Svelte组件包含呈现一部分UI所需的全部。 每个Svelte组件都在.svelte文件中声明,在那里您可以找到内容(标记),行为(JavaScript)和表示形式(CSS),而不必定义单独的文件。

Which is a sane way to define a piece of the UI because you don't need to search for the items that affect the same element across various files.

这是定义一部分UI的明智方法,因为您无需搜索影响各个文件中相同元素的项目。

Here's a sample component, which we'll store in a file called Dog.svelte:

这是一个示例组件,我们将其存储在一个名为Dog.svelte的文件中:

<script>
export let name;
</script>

<style>
h1 {
  color: purple;
}
</style>

<h1>The dog name is {name}!</h1>

Any JavaScript must be put in the script tag.

必须将任何JavaScript放在script标记中。

The CSS you have in the style tag is scoped to the component and does not "leak" outside. If another component has an h1 tag, this style will not affect that. This is very handy when reusing components you already wrote for other applications, for example, or when you include Open Source libraries published by other people.

您在style标签中使用CSS的作用域是该组件,并且不会“泄漏”到外部。 如果另一个组件具有h1标签,则此样式不会对此产生影响。 例如,在重复使用已经为其他应用程序编写的组件时,或者在包含其他人发布的开放源代码库时,这非常方便。

For example, a few weeks ago I included a date picker component built with Svelte in an application and none of the stylings of the component leaked outside of it, and none of the CSS I wrote into the app modified the look of the date picker.

例如,几周前,我在应用程序中包括了一个使用Svelte构建的日期选择器组件,该组件的样式均未泄漏到该组件之外,并且我写入该应用程序CSS都没有修改日期选择器的外观。

将组件导入其他组件 (Importing the component in other components)

A component can, as said, be used by other components.

如上所述,一个组件可以被其他组件使用。

Other components can now import the Dog component in their code.

现在,其他组件可以在其代码中导入Dog组件。

For example here's a House component, defined in a House.svelte file, in the same folder of Dog.svelte:

比如这里有一个House组件,在规定的House.svelte文件,在同一个文件夹Dog.svelte

<script>
import Dog from './Dog.svelte'
</script>

You can now use the Dog component like an HTML tag:

现在,您可以像HTML标签一样使用Dog组件:

<script>
import Dog from './Dog.svelte'
</script>

<Dog />

从组件导出特定功能 (Exporting specific functions from a component)

As you saw above, to export the component we didn't have to do anything, because the component itself is the default export.

正如您在上面看到的,导出组件无需执行任何操作,因为组件本身是默认的export

What if you want to export something other than the component markup and its associated and built-in functionality?

如果要导出组件标记及其关联和内置功能以外的内容,该怎么办?

You must write all the functions you want to export from a special script tag with the context="module" attribute.

您必须使用context="module"属性script要从特殊script标记导出的所有函数。

Here's an example. Say you have a Button component in Button.svelte:

这是一个例子。 假设您在Button.svelte有一个Button组件:

<button>A button</button>

and you want to provide other components the ability to change the color of the button.

并且您想为其他组件提供更改按钮颜色的功能。

A better solution for this use case is to use props, which is something we'll talk about in the next chapter. But stick with me for this example

对于这种用例,更好的解决方案是使用道具,这将在下一章中讨论。 但是在这个例子中坚持我

You can provide a function, called changeColor.

您可以提供一个名为changeColor的函数。

You write and export it in this special script tag:

您可以在以下特殊script标记中编写和导出它:

<script context="module">
export function changeColor() {
  //...logic to change color..
}
</script>

<button>A button</button>

Note that you can have another "normal" script tag, in the component.

请注意,您可以在组件中拥有另一个“普通”脚本标签。

Now other components can import Button, which is the default export, and the changeColor function too:

现在其他组件可以导入Button(这是默认导出),也可以导入changeColor函数:

<script>
import Button, { changeColor } from './Button.svelte'
</script>

Now that is probably a silly example, but knowing you have this functionality at your disposal can be quite helpful.

现在这可能是一个愚蠢的示例,但是了解您拥有的此功能可能会很有帮助。

Card.svelte的处理状态 (Handling State in Svelte)

Every component, in addition to defining the markup, the CSS and the JavaScript logic, can host its own state.

除了定义标记,CSS和JavaScript逻辑之外,每个组件都可以承载自己的状态

What is state? State is any data that's needed to make the component render what it's rendering.

什么是状态? 状态是使组件呈现其呈现状态所需的任何数据。

For example, if a form input field has the string "test" written into it, there'll be a variable somewhere holding this value. That's the state of the input field.

例如,如果表单输入字段中写入了字符串“ test”,则在该位置将有一个变量。 这就是输入字段的状态。

The field is selected? A variable somewhere will register this fact. And so on.

该字段被选中? 某个地方的变量将记录此事实。 等等。

State is hosted in the script part of a component:

状态托管在组件的script部分中:

<script>
let count = 0
</script>

Now, if you come from other frameworks in the frontend space like Vue or React, you might think "how do I update this value?" - and for a good reason, as those frameworks make this operation rather unintuitive, I'd say.

现在,如果您来自前端空间中的其他框架(如Vue或React),您可能会认为“如何更新此值?” -我会说,这是有充分的理由的,因为这些框架使此操作相当不直观。

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. A simple JavaScript assignment, using the = operator for example.

您所需要做的只是一项任务。 一个简单JavaScript赋值,例如使用=运算符。

Say you have a count variable. You can increment that using, simply, count = count + 1, or count++:

假设您有一个count变量。 您可以简单地使用count = count + 1count++来增加它:

<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 make an assignment when changing the value.

我们需要注意一件事,这很快就会学到:更改值时还必须进行赋值。

Svelte always wants an assignment, otherwise it might not recognize that the state changed.

Svelte总是需要分配,否则可能无法识别状态已更改。

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]

苗条的React性 (Svelte Reactivity)

In Svelte you can listen for changes in the component state, and update other variables.

在Svelte中,您可以侦听组件状态的变化,并更新其他变量。

For example if you have a count variable:

例如,如果您有一个count变量:

<script>
let count = 0
</script>

and you update it by clicking a button:

然后您通过单击按钮进行更新:

<script>
let count = 0

const incrementCount = () => {
  count = count + 1
}
</script>

{count} <button on:click={incrementCount}>+1</button>

You can listen for changes on count using the special syntax $: which defines a new block that Svelte will re-run when any variable referenced into it changes.

您可以使用特殊语法$:监听count变化$:它定义了一个新块,当引用到它的任何变量发生变化时,Svelte都会重新运行。

Here's an example:

这是一个例子:

<script>
let count = 0

const incrementCount = () => {
  count = count + 1
}

$: console.log(`${count}`)
</script>

{count} <button on:click={incrementCount}>+1</button>

I used the block:

我用了块:

$: console.log(`${count}`)

You can write more than one of them:

您可以编写其中一个以上的代码:

<script>
$: console.log(`the count is ${count}`)
$: console.log(`double the count is ${count * 2}`)
</script>

And you can also add a block to group more than one statement:

您还可以添加一个块来组合多个语句:

<script>
$: {
  console.log(`the count is ${count}`)
  console.log(`double the count is ${count * 2}`)
}
</script>

I used a console.log() call in there, but you can update other variables too:

我在那里使用了console.log()调用,但是您也可以更新其他变量:

<script>
let count = 0
let double = 0

$: {
  console.log(`the count is ${count}`)
  double = count * 2
  console.log(`double the count is ${double}`)
}
</script>

苗条的道具 (Svelte Props)

You can import a Svelte component into any other component using the syntax import ComponentName from 'componentPath':

您可以使用import ComponentName from 'componentPath'的语法import ComponentName from 'componentPath'将Svelte组件导入任何其他组件:

<script>
import SignupForm from './SignupForm.svelte';
</script>

The path is relative to the current component path. ./ means "this same folder". You'd use ../ to go back one folder, and so on.

该路径是相对于当前组件路径的。 ./表示“该文件夹”。 您将使用../返回一个文件夹,依此类推。

Once you do so, you can use the newly imported component in the markup, like an HTML tag:

完成后,您可以在标记中使用新导入的组件,例如HTML标签:

<SignupForm />

In this way, you are forming a parent/child relationship between the two components: the one that imports, and the one that is imported.

通过这种方式,您将在两个组件之间形成父/子关系:一个是导入的,另一个是导入的。

Often you want to have the parent component pass data to the child component.

通常,您希望让父组件将数据传递给子组件。

You can do so using props. Props behave similarly to attributes in plain HTML, and they are a one-way form of communication.

您可以使用道具来这样做。 道具的行为与纯HTML中的属性类似,它们是一种单向通信形式。

In this example we pass the disabled prop, passing the JavaScript value true to it:

在此示例中,我们传递了disabled prop,并将JavaScript值true传递给了它:

<SignupForm disabled={true}/>

In the SignupForm component, you need to export the disabled prop, in this way:

在SignupForm组件中,您需要通过以下方式导出 disabled道具:

<script>
  export let disabled
</script>

This is the way you express the fact that the prop is exposed to parent components.

这是您表达道具暴露于父部件的事实的方式。

When using the component, you can pass a variable instead of a value, to change it dynamically:

使用组件时,可以传递变量而不是值来动态更改它:

<script>
import SignupForm from './SignupForm.svelte';
let disabled = true
</script>

<SignupForm disabled={disabled}/>

When the disabled variable value changes, the child component will be updated with the new prop value. Example:

disabled变量值更改时,子组件将使用新的prop值进行更新。 例:

<script>
import SignupForm from './SignupForm.svelte';
let disabled = true
setTimeout(() => { disabled = false }, 2000)
</script>

<SignupForm disabled={disabled}/>

Card.svelte的跨组件状态管理 (Cross-component State Management in Svelte)

We've already seen how Svelte makes handling the state of a single component very easy.

我们已经看到了Svelte如何使处理单个组件的状态变得非常容易。

But how do we pass state around across components?

但是,我们如何在组件之间传递状态呢?

使用道具传递状态 (Passing state around using props)

The first strategy is common to other UI frameworks, and it's passing state around using props, lifting the state up.

第一种策略是其他UI框架所共有的,它使用props传递状态,从而提升状态

When a component needs to share data with another, the state can be moved up in the components tree until there's a common parent to those components.

当一个组件需要与另一个组件共享数据时,可以在组件树中将状态上移,直到这些组件有一个公共父级。

The state needs to be passed down until it reaches all the components that need this state information.

需要向下传递状态,直到到达需要此状态信息的所有组件为止。

This is done using props, and it's a technique that I think is the best as it's simple.

这是使用props完成的,并且我认为这是一种最好的技术,因为它很简单。

上下文API (The context API)

However, there are cases where props are not practical. Perhaps 2 components are so distant in the components tree that we'd have to move state up to the top-level component.

但是,在某些情况下道具不实用。 也许2个组件在组件树中距离太远,以至于我们不得不将状态移到顶层组件。

In this case, another technique can be used called context API. It's ideal when you want to let multiple components communicate with descendants, but you don't want to pass props around.

在这种情况下,可以使用另一种称为上下文API的技术。 当您想让多个组件与后代进行通信,但又不想传递道具时,这是理想的选择。

The context API is provided by 2 functions which are provided by the svelte package: getContext and setContext.

上下文API由svelte包提供的2个函数提供: getContextsetContext

You set an object in the context, associating it to a key:

您在上下文中设置一个对象,并将其与键关联:

<script>
import { setContext } from 'svelte'

const someObject = {}

setContext('someKey', someObject)
</script>

In another component you can use getContext to retrieve the object assigned to a key:

在另一个组件中,可以使用getContext检索分配给键的对象:

<script>
import { getContext } from 'svelte'

const someObject = getContext('someKey')
</script>

You can only use getContext to retrieve a key either in the component that used setContext or in one of its descendants.

您只能使用getContext在使用setContext的组件或其后代之一中检索键。

If you want to let two components living in 2 different component trees communicate there's another tool for us: stores.

如果您想让生活在2个不同组件树中的两个组件进行通信,那么还有另一种工具供我们使用: store

使用Svelte商店 (Using Svelte stores)

Svelte stores are a great tool to handle your app state when components need to talk to each other without passing props around too much.

Svelte商店是一个很好的工具,可以在组件需要相互通信而又不会过多传递道具时处理您的应用程序状态。

You must first import writable from svelte/store:

您必须首先从svelte/store导入writable

import { writable } from 'svelte/store'

and create a store variable using the writable() function, passing the default value as the first argument:

并使用writable()函数创建存储变量,并将默认值作为第一个参数传递:

const username = writable('Guest')

This can be put into a separate file which you can import into multiple components, for example, called store.js (it's not a component, so it can be in a .js file instead of .svelte):

可以将其放入一个单独的文件中,您可以将其导入多个组件,例如,称为store.js (它不是组件,因此可以在.js文件而不是.svelte ):

import { writable } from 'svelte/store'
export const username = writable('Guest')

Any other component now loading this file can access the store:

现在正在加载此文件的任何其他组件都可以访问商店:

<script>
import { username } from './store.js'
</script>

Now the value of this variable can be set to a new value using set(), passing the new value as the first argument:

现在可以使用set()将此变量的值设置为新值,并将新值作为第一个参数传递:

username.set('new username')

And it can be updated using the update() function, which differs from set() because you don't just pass the new value to it - you run a callback function that is passed the current value as its argument:

而且可以使用update()函数进行更新,该函数与set()不同,因为您不只是将新值传递给它-您运行的回调函数会将当前值作为其参数传递:

const newUsername = 'new username!'
username.update(existing => newUsername)

You can add more logic here:

您可以在此处添加更多逻辑:

username.update(existing => {
  console.log(`Updating username from ${existing} to ${newUsername}`)
  return newUsername
})

To get the value of the store variable once, you can use the get() function exported by svelte/store:

拿到店里变量的值一次 ,就可以使用get()的导出函数svelte/store

import { writable, get } from 'svelte/store'
export const username = writable('Guest')
get(username) //'Guest'

To create a reactive variable that's updated whenever the store value changes instead, you can prepend the store variable using $ (in this example $username). Using that will make the component re-render whenever the stored value changes.

要创建一个每当商店值更改时都会更新的React型变量,您可以在商店变量前使用$ (在本示例中$username )。 使用该属性将使存储值更改时重新渲染组件。

Svelte considers $ to be a reserved value and will prevent you from using it for things that are not related to stores values (which might lead to confusion). So if you are used to prepending DOM references using $, don't do it in Svelte.

Svelte认为$是保留值,将阻止您将其用于与商店值无关的事情(这可能会引起混乱)。 因此,如果您习惯使用$来添加DOM引用,请不要在Svelte中这样做。

Another option, best suited if you need to execute some logic when the variable changes, is to use the subscribe() method of username:

如果您需要在变量更改时执行一些逻辑,那么最适合的另一种选择是使用usernamesubscribe()方法:

username.subscribe(newValue => {
  console.log(newValue)
})

In addition to writable stores, Svelte provides 2 special kinds of stores: readable stores and derived stores.

除了可写存储外,Svelte还提供2种特殊类型的存储: 可读存储派生存储

苗条的可读商店 (Svelte Readable Stores)

Readable stores are special because they can't be updated from the outside - there's no set() or update() method. Instead, once you set the initial state, they can't be modified from the outside.

可读存储很特殊,因为它们不能从外部进行更新-没有set()update()方法。 相反,一旦设置了初始状态,便无法从外部对其进行修改。

The official Svelte docs show an interesting example using a timer to update a date. I can think of setting up a timer to fetch a resource from the network, perform an API call, get data from the filesystem (using a local Node.js server) or anything else that can be set up autonomously.

Svelte官方文档显示了一个有趣的示例,该示例使用计时器来更新日期。 我可以考虑设置一个计时器,以从网络中获取资源,执行API调用,从文件系统获取数据(使用本地Node.js服务器)或其他任何可以自动设置的内容。

In this case, instead of using writable() to initialize the store variable, we use readable():

在这种情况下,我们不是使用writable()初始化存储变量,而是使用readable()

import { readable } from 'svelte/store'
export const count = readable(0)

You can provide a function after the default value that will be responsible for updating it. This function receives the set function to modify the value:

您可以在默认值之后提供一个函数,以负责对其进行更新。 此函数接收set函数来修改值:

<script>
import { readable } from 'svelte/store'
export const count = readable(0, set => {
  setTimeout(() => {
    set(1)
  }, 1000)
})
</script>

In this case, we update the value from 0 to 1 after 1 second.

在这种情况下,我们会在1秒后将值从0更新为1。

You can setup an interval in this function, too:

您也可以在此功能中设置间隔:

import { readable, get } from 'svelte/store'
export const count = readable(0, set => {
  setInterval(() => {
    set(get(count) + 1)
  }, 1000)
})

You can use this in another component like this:

您可以在其他组件中使用它,如下所示:

<script>
import { count } from './store.js'
</script>

{$count}

Card.svelte派生商店 (Svelte Derived Stores)

A derived store allows you to create a new store value that depends on the value of an existing store.

派生商店允许您创建一个新的商店值,该值取决于现有商店的值。

You can do so using the derived() function exported by svelte/store which takes as its first parameter the existing store value, and as a second parameter a function which receives that store value as its first parameter:

您可以使用svelte/store导出的derived()函数derived()将现有存储值作为第一个参数,并将接收该存储值作为第一个参数的函数作为第二个参数:

import { writable, derived } from 'svelte/store'

export const username = writable('Guest')

export const welcomeMessage = derived(username, $username => {
  return `Welcome ${$username}`
})
<script>
import { username, welcomeMessage } from './store.js'
</script>

{$username}
{$welcomeMessage}

苗条的插槽 (Svelte Slots)

Slots are a handy way to let you define components that can be composed together.

插槽是一种方便的方法,可让您定义可以组合在一起的组件。

And vice versa, depending on your point of view, slots are a handy way to configure a component you are importing.

反之亦然,根据您的观点,插槽是配置导入组件的便捷方法。

Here's how they work.

这是他们的工作方式。

In a component you can define a slot using the <slot /> (or <slot></slot>) syntax.

在组件中,可以使用<slot /> (或<slot></slot> )语法定义<slot></slot>

Here's a Button.svelte component that simply prints a <button> HTML tag:

这是一个Button.svelte组件,它仅打印一个<button> HTML标记:

<button><slot /></button>

For React developers, this is basically the same as <button>{props.children}</button>

对于React开发人员,这基本上与<button>{props.children}</button>

Any component importing it can define content that is going to be put into the slot by adding it into the component's opening and closing tags:

任何导入它的组件都可以通过将其添加到组件的开始和结束标记中来定义将要放入插槽的内容:

<script>
import Button from './Button.svelte'
</script>

<Button>Insert this into the slot</Button>

You can define a default, which is used if the slot is not filled:

您可以定义一个默认值,如果未填充插槽,则使用该默认值:

<button>
  <slot>
    Default text for the button
  </slot>
</button>

You can have more than one slot in a component, and you can distinguish one from the other using named slots. The single unnamed slot will be the default one:

一个组件中可以有多个插槽,并且可以使用命名插槽将一个插槽与另一个插槽区分开。 单个未命名的插槽将是默认插槽:

<slot name="before" />
<button>
  <slot />
</button>
<slot name="after" />

Here's how you would use it:

使用方法如下:

<script>
import Button from './Button.svelte'
</script>

<Button>
  Insert this into the slot
  <p slot="before">Add this before</p>
  <p slot="after">Add this after</p>
</Button>

And this would render the following to the DOM:

这会将以下内容呈现给DOM:

<p slot="before">Add this before</p>
<button>
  Insert this into the slot
</button>
<p slot="after">Add this after</p>

苗条的生命周期事件 (Svelte Lifecycle Events)

Every component in Svelte fires several lifecycle events that we can hook on, to help us implement the functionality we have in mind.

Svelte中的每个组件都会触发几个我们可以挂钩的生命周期事件,以帮助我们实现我们所想到的功能。

In particular, we have

特别是,我们有

  • onMount fired after the component is rendered

    渲染组件后触发onMount

  • onDestroy fired after the component is destroyed

    销毁组件后触发onDestroy

  • beforeUpdate fired before the DOM is updated

    在DOM更新之前触发了beforeUpdate

  • afterUpdate fired after the DOM is updated

    DOM更新后触发afterUpdate

We can schedule functions to happen when these events are fired by Svelte.

我们可以安排函数在Svelte触发这些事件时发生。

We don't have access to any of those methods by default, but we need to import them from the svelte package:

默认情况下,我们无权访问任何这些方法,但是我们需要从svelte包中导入它们:

<script>
  import { onMount, onDestroy, beforeUpdate, afterUpdate } from 'svelte'
</script>

A common scenario for onMount is to fetch data from other sources.

onMount的常见方案是从其他来源获取数据。

Here's a sample usage of onMount:

这是onMount的示例用法:

<script>
  import { onMount } from 'svelte'

  onMount(async () => {
    //do something on mount
  })
</script>

onDestroy allows us to clean up data or stop any operation we might have started at the component initialization, like timers or scheduled periodic functions using setInterval.

onDestroy允许我们清理数据或停止在组件初始化时可能已开始的任何操作,例如使用setInterval计时器或计划的定期函数。

One particular thing to notice is that if we return a function from onMount, that serves the same functionality of onDestroy - it's run when the component is destroyed:

需要注意的一件事是,如果我们从onMount返回一个函数,该函数提供与onDestroy相同的功能-它在销毁组件时运行:

<script>
  import { onMount } from 'svelte'

  onMount(async () => {
    //do something on mount

    return () => {
      //do something on destroy
    }
  })
</script>

Here's a practical example that sets a periodic function to run on mount, and removes it on destroy:

这是一个实际的示例,该示例将周期函数设置为在安装时运行,并在销毁时将其删除:

<script>
  import { onMount } from 'svelte'

  onMount(async () => {
    const interval = setInterval(() => {
      console.log('hey, just checking!')
    }, 1000)

    return () => {
      clearInterval(interval)
    }
  })
</script>

苗条的绑定 (Svelte Bindings)

Using Svelte you can create a two-way binding between data and the UI.

使用Svelte,您可以在数据和UI之间创建双向绑定。

Many other Web frameworks can provide two-way bindings, it's a very common pattern.

许多其他Web框架可以提供双向绑定,这是一种非常常见的模式。

They are especially useful with forms.

它们对于表格特别有用。

绑定:值 (bind:value)

Let's start with the most common form of binding you'll often use, which you can apply using bind:value. You take a variable from the component state, and you bind it to a form field:

让我们从最常用的绑定形式开始,您可以使用bind:value来应用它。 您从组件状态获取变量,并将其绑定到表单字段:

<script>
let name = ''
</script>

<input bind:value={name}>

Now if name changes, the input field will update its value. And the opposite is true, as well: if the form is updated by the user, the name variable value changes.

现在,如果name更改,则输入字段将更新其值。 反之亦然:如果表单由用户更新,则name变量值会更改。

Just be aware that the variable must be defined using let/var and not const, otherwise it can't be updated by Svelte, as const defines a variable with a value that can't be reassigned.

请注意,该变量必须使用let/var而不是const进行定义,否则Svelte无法对其进行更新,因为const定义了一个变量,其值无法重新分配。

bind:value works on all flavors of input fields (type="number", type="email" and so on), but it also works for other kind of fields, like textarea and select (more on select later).

bind:value输入字段(所有口味的作品type="number"type="email"等),但它也适用于其他类型的字段,如textareaselect (更多select更高版本)。

复选框和单选按钮 (Checkboxes and radio buttons)

Checkboxes and radio inputs (input elements with type="checkbox" or type="radio") allow those 3 bindings:

复选框和单选输入( type="checkbox"type="radio" input元素)允许这3种绑定:

  • bind:checked

    bind:checked

  • bind:group

    bind:group

  • bind:indeterminate

    bind:indeterminate

bind:checked allows us to bind a value to the checked state of the element:

bind:checked允许我们将值绑定到元素的检查状态:

<script>
let isChecked
</script>

<input type=checkbox bind:checked={isChecked}>

bind:group is handy with checkboxes and radio inputs, because those are very often used in groups. Using bind:group you can associate a JavaScript array to a list of checkboxes, and have it populated based on the choices made by the user.

bind:group易于使用复选框和单选输入,因为它们经常在组中使用。 使用bind:group可以将JavaScript数组与复选框列表关联,并根据用户的选择进行填充。

Here's an example. The goodDogs array populates based on the checkboxes I tick:

这是一个例子。 goodDogs数组根据我打勾的复选框进行填充:

<script>
let goodDogs = []
let dogs = ['Roger', 'Syd']
</script>

<h2>
  Who's a good dog?
</h2>

<ul>
  {#each dogs as dog}
    <li>{dog} <input type=checkbox bind:group={goodDogs} value={dog}></li>
  {/each}
</ul>

<h2>
  Good dogs according to me:
</h2>

<ul>
  {#each goodDogs as dog}
    <li>{dog}</li>
  {/each}
</ul>

See the example on https://svelte.dev/repl/059c1b5edffc4b058ad36301dd7a1a58

参见https://svelte.dev/repl/059c1b5edffc4b058ad36301dd7a1a58上的示例

bind:indeterminate allows us to bind to the indeterminate state of an element (if you want to learn more head to https://css-tricks.com/indeterminate-checkboxes/).

bind:indeterminate允许我们绑定到元素的indeterminate状态(如果您想了解更多信息, 转至https://css-tricks.com/indeterminate-checkboxes/ )。

选择栏位 (Select fields)

bind:value also works for the select form field to get the selected value automatically assigned to the value of a variable:

bind:value也适用于select表单字段,以获取自动分配给变量值的选定值:

<script>
let selected
</script>

<select bind:value={selected}>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

{selected}

The cool thing is that if you generate options dynamically from an array of objects, the selected option is now an object, not a string:

很棒的事情是,如果您从对象数组动态生成选项,则所选选项现在是一个对象,而不是字符串:

<script>
let selected

const goodDogs = [
  { name: 'Roger' },
  { name: 'Syd' }
]
</script>

<h2>List of possible good dogs:</h2>
<select bind:value={selected}>
  {#each goodDogs as goodDog}
    <option value={goodDog}>{goodDog.name}</option>
  {/each}
</select>

{#if selected}
<h2>
  Good dog selected: {selected.name}
</h2>
{/if}

See example: https://svelte.dev/repl/7e06f9b7becd4c57880db5ed184ea0f3

参见示例: https : //svelte.dev/repl/7e06f9b7becd4c57880db5ed184ea0f3

select also allows the multiple attribute:

select还允许使用multiple属性:

<script>
let selected = []

const goodDogs = [
  { name: 'Roger' },
  { name: 'Syd' }
]
</script>

<h2>List of possible good dogs:</h2>
<select multiple bind:value={selected}>
  {#each goodDogs as goodDog}
    <option value={goodDog}>{goodDog.name}</option>
  {/each}
</select>

{#if selected.length}
<h2>Good dog selected:</h2>
<ul>
  {#each selected as dog}
    <li>{dog.name}</li>
  {/each}
</ul>
{/if}

See example:  https://svelte.dev/repl/b003248e87f04919a2f9fed63dbdab8c

查看范例: https//svelte.dev/repl/b003248e87f04919a2f9fed63dbdab8c

其他绑定 (Other bindings)

Depending on the HTML tag you are working on, you can apply different kinds of bindings.

根据您正在处理HTML标记,您可以应用不同种类的绑定。

bind:files is a binding valid on type="file" input elements, to bind the list of selected files.

bind:files是对type="file"输入元素有效的绑定,用于绑定所选文件的列表。

The details HTML element allows the use of bind:open to bind its open/close value.

details HTML元素允许使用bind:open绑定其打开/关闭值。

The audio and video media HTML tags allow us to bind several of their properties: currentTime, duration, paused, buffered, seekable, played, volume, playbackRate.

audiovideo媒体HTML标签允许我们绑定它们的几个属性: currentTimedurationpausedbufferedseekableplayedvolumeplaybackRate

textContent and innerHTML can be bound on contenteditable fields.

textContentinnerHTML可以绑定在contenteditable字段上。

All very useful things for those specific HTML elements.

这些特定HTML元素的所有非常有用的东西。

只读绑定 (Read-only bindings)

offsetWidth, offsetHeight, clientWidth, clientHeight can be bound, read only, on any block level HTML element, excluding void tags (like br) and elements that are set to be inline (display: inline).

offsetWidthoffsetHeightclientWidthclientHeight可以在任何块级HTML元素上绑定(只读),不包括void标签(如br )和设置为内联的元素( display: inline )。

获取对JavaScript中HTML元素的引用 (Get a reference to the HTML element in JavaScript)

bind:this is a special kind of binding that allows you to get a reference to an HTML element and bind it to a JavaScript variable:

bind:this是一种特殊的绑定,它允许您获取对HTML元素的引用并将其绑定到JavaScript变量:

<script>
let myInputField
</script>

<input bind:this={myInputField} />

This is handy when you need to apply logic to elements after you mount them, for example, using the onMount() lifecycle event callback.

当您在安装元素后需要将逻辑应用于元素时(例如,使用onMount()生命周期事件回调onMount() ,这非常方便。

装订道具 (Binding components props)

Using bind: you can bind a value to any prop that a component exposes.

使用bind:您可以将值绑定到组件公开的任何prop。

Say you have a Car.svelte component:

假设您有一个Car.svelte组件:

<script>
export let inMovement = false
</script>

<button on:click={() => inMovement = true }>Start car</button>

You can import the component and bind the inMovement prop:

您可以导入组件并绑定inMovement

<script>
  import Car from './Car.svelte';

  let carInMovement;
</script>

<Car bind:inMovement={carInMovement} />

{carInMovement}

This can allow for interesting scenarios.

这可以考虑一些有趣的情况。

模板中的条件逻辑 (Conditional Logic in Templates)

In a Svelte component, when it comes to rendering HTML you can work with some specific syntax to craft the UI you need at every stage of the application lifecycle.

在Svelte组件中,涉及呈现HTML时,您可以使用一些特定的语法来设计在应用程序生命周期的每个阶段所需的UI。

In particular, we'll now explore conditional structures.

特别是,我们现在将探讨条件结构。

The problem is this: you want to be able to look at a value/expression, and if that points to a true value do something, if that points to a false value then do something else.

问题是这样的:您希望能够查看一个值/表达式,并且如果该值/值指向一个真值,则执行某些操作,如果该值/值指向一个假值,则执行其他操作。

Svelte provides us a very powerful set of control structures.

Svelte为我们提供了非常强大的控制结构集。

The first is if:

第一个是,如果

{#if isRed}
  <p>Red</p>
{/if}

There is an opening {#if} and an ending {/if}. The opening markup checks for a value or statement to be truthy. In this case isRed can be a boolean with a true value:

有一个开头{#if}和一个结尾{/if} 。 开头标记检查值或语句是否真实。 在这种情况下, isRed可以是具有true值的布尔值:

<script>
let isRed = true
</script>

An empty string is falsy, but a string with some content is truthy.

空字符串是虚假的,但包含某些内容的字符串是虚假的。

0 is falsy, but a number > 0 is truthy.

0是虚假的,但数字> 0是真实的。

The boolean value true is truthy, of course, and false is falsy.

布尔值true当然是真实的,而false是虚假的。

If the opening markup is not satisfied (a falsy value is provided), then nothing happens.

如果不满足打开标记(提供虚假值),则什么都不会发生。

To do something else if that's not satisfied, we use the appropriately called else statement:

如果不满意,可以做其他事情,我们使用适当地调用else语句:

{#if isRed}
  <p>Red</p>
{:else}
  <p>Not red</p>
{/if}

Either the first block is rendered in the template or the second one. There's no other option.

第一个块将在模板中呈现,或者第二个块将在模板中呈现。 没有其他选择。

You can use any JavaScript expression into the if block condition, so you can negate an option using the ! operator:

您可以在if块条件中使用任何JavaScript表达式,因此可以使用!取消选项! 操作员:

{#if !isRed}
  <p>Not red</p>
{:else}
  <p>Red</p>
{/if}

Now, inside the else you might want to check for an additional condition. That's where the {:else if somethingElse} syntax comes along:

现在,在else内部,您可能想要检查其他条件。 这就是{:else if somethingElse}语法的来源:

{#if isRed}
  <p>Red</p>
{:else if isGreen}
  <p>Green</p>
{:else}
  <p>Not red nor green</p>
{/if}

You can have many of these blocks, not just one, and you can nest them. Here's a more complex example:

您可以有许多这样的块,而不仅仅是一个,并且可以嵌套它们。 这是一个更复杂的示例:

{#if isRed}
  <p>Red</p>
{:else if isGreen}
  <p>Green</p>
{:else if isBlue}
  <p>It is blue</p>
{:else}
  {#if isDog}
    <p>It is a dog</p>
  {/if}
{/if}

Svelte模板中的循环 (Looping in Svelte Templates)

In Svelte templates you can create a loop using the {#each}{/each} syntax:

在Svelte模板中,您可以使用{#each}{/each}语法创建循环:

<script>
let goodDogs = ['Roger', 'Syd']
</script>

{#each goodDogs as goodDog}
  <li>{goodDog}</li>
{/each}

If you are familiar with other frameworks that use templates, it's a very similar syntax.

如果您熟悉使用模板的其他框架,则其语法非常相似。

You can get the index of the iteration using:

您可以使用以下方法获取迭代的索引:

<script>
let goodDogs = ['Roger', 'Syd']
</script>

{#each goodDogs as goodDog, index}
  <li>{index}: {goodDog}</li>
{/each}

(indexes start at 0)

(索引从0开始)

When dynamically editing the lists removing and adding elements, you should always pass an identifier in lists to prevent issues.

动态编辑列表中的删除和添加元素时,应始终在列表中传递标识符以防止出现问题。

You do so using this syntax:

您可以使用以下语法:

<script>
let goodDogs = ['Roger', 'Syd']
</script>

{#each goodDogs as goodDog (goodDog)}
  <li>{goodDog}</li>
{/each}

<!-- with the index -->
{#each goodDogs as goodDog, index (goodDog)}
  <li>{goodDog}</li>
{/each}

You can pass an object, too, but if your list has a unique identifier for each element, it's best to use it:

您也可以传递一个对象,但是如果列表中每个元素都有一个唯一的标识符,则最好使用它:

<script>
let goodDogs = [
  { id: 1, name: 'Roger'},
  { id: 2, name: 'Syd'}
]
</script>

{#each goodDogs as goodDog (goodDog.id)}
  <li>{goodDog.name}</li>
{/each}

<!-- with the index -->
{#each goodDogs as goodDog, index (goodDog.id)}
  <li>{goodDog.name}</li>
{/each}

Svelte模板中的承诺 (Promises in Svelte Templates)

Promises are an awesome tool we have at our disposal to work with asynchronous events in JavaScript.

Promise是一个很棒的工具,可用于处理JavaScript中的异步事件。

The relatively recent introduction of the await syntax in ES2017 made using promises even simpler.

ES2017中相对较新的await语法介绍使使用promise更加简单。

Svelte gives us the {#await} syntax in templates to directly work with promises at the template level.

Svelte在模板中为我们提供了{#await}语法,可直接在模板级别上使用promise。

We can wait for promises to resolve, and define a different UI for the various states of a promise: unresolved, resolved, and rejected.

我们可以等待承诺解决,并为承诺的各种状态定义不同的UI:未解决,已解决和已拒绝。

Here's how it works. We define a promise, and using the {#await} block we wait for it to resolve.

运作方式如下。 我们定义一个承诺,并使用{#await}块等待它解决。

Once the promise resolves, the result is passed to the {:then} block:

承诺解决后,结果将传递到{:then}块:

<script>
  const fetchImage = (async () => {
    const response = await fetch('https://dog.ceo/api/breeds/image/random')
    return await response.json()
  })()
</script>

{#await fetchImage}
  <p>...waiting</p>
{:then data}
  <img src={data.message} alt="Dog image" />
{/await}

You can detect a promise rejection by adding a {:catch} block:

您可以通过添加{:catch}块来检测承诺被拒绝:

{#await fetchImage}
  <p>...waiting</p>
{:then data}
  <img src={data.message} alt="Dog image" />
{:catch error}
  <p>An error occurred!</p>
{/await}

Run the example: https://svelte.dev/repl/70e61d6cc91345cdaca2db9b7077a941

运行示例: https : //svelte.dev/repl/70e61d6cc91345cdaca2db9b7077a941

在Card.svelte活动 (Working with Events in Svelte)

监听DOM事件 (Listening to DOM events)

In Svelte you can define a listener for a DOM event directly in the template, using the on:<event> syntax.

在Svelte中,您可以使用on:<event>语法直接在模板中为DOM事件定义侦听器。

For example, to listen to the click event, you will pass a function to the on:click attribute.

例如,要监听click事件,您需要将一个函数传递给on:click属性。

To listen to the onmousemove event, you'll pass a function to the on:mousemove attribute.

要监听onmousemove事件,您需要将一个函数传递给on:mousemove属性。

Here's an example with the handling function defined inline:

这是内联定义处理函数的示例:

<button on:click={() => {
  alert('clicked')
}}>Click me</button>

and here's another example with the handling function defined in the script section of the component:

这是在组件的script部分中定义的处理函数的另一个示例:

<script>
const doSomething = () => {
  alert('clicked')
}
</script>

<button on:click={doSomething}>Click me</button>

I prefer inline when the code is not too verbose. If it's just 2-3 lines, for example - otherwise I'd move that up in the script section.

当代码不太冗长时,我更喜欢内联。 例如,如果只有2-3行-否则我将在脚本部分中将其上移。

Svelte passes the event handler as the argument of the function, which is handy if you need to stop propagation or to reference something in the Event object:

Svelte将事件处理程序作为函数的参数传递,如果您需要停止传播或在Event对象中引用某些内容,这将非常方便:

<script>
const doSomething = event => {
  console.log(event)
  alert('clicked')
}
</script>

<button on:click={doSomething}>Click me</button>

Now, I mentioned "stop propagation". That's a very common thing to do, to stop form submit events for example. Svelte provides us modifiers, a way to apply it directly without manually doing it.stopPropagation and preventDefault are the 2 modifiers you'll use the most, I think.

现在,我提到了“停止传播”。 这是很常见的事情,例如停止表单提交事件。 Svelte为我们提供了修饰符 ,这是一种无需手动执行即可直接应用它的方法。 我认为stopPropagationpreventDefault是您最常使用的2个修饰符。

You apply a modifier like this: <button on:click|stopPropagation|preventDefault={doSomething}>Click me</button>

您可以应用如下修饰符: <button on:click|stopPropagation|preventDefault={doSomething}>Click me</button>

There are other modifiers, which are more niche. capture enables capturing events instead of bubbling, once only fires the event once, self only fires the event if the target of the event is this object (removing it from the bubbling/capturing hierarchy).

还有其他修饰符,这些修饰符更合适。 capture启用捕获事件而不是冒泡once仅触发一次事件,如果事件的目标是此对象,则self仅触发事件(将其从冒泡/捕获层次结构中删除)。

在组件中创建事件 (Creating your events in components)

What's interesting is that we can create custom events in components, and use the same syntax of built-in DOM events.

有趣的是,我们可以在组件中创建自定义事件,并使用内置DOM事件的相同语法。

To do so, we must import the createEventDispatcher function from the svelte package and call it to get an event dispatcher:

为此,我们必须从svelte包中导入createEventDispatcher函数并调用它以获取事件分配器:

<script>
  import { createEventDispatcher } from 'svelte'
  const dispatch = createEventDispatcher()
</script>

Once we do so, we can call the dispatch() function, passing a string that identifies the event (which we'll use for the on: syntax in other components that use this):

完成后,我们可以调用dispatch()函数,并传递一个用于标识事件的字符串(我们将在使用该函数的其他组件中使用on:语法):

<script>
  import { createEventDispatcher } from 'svelte'
  const dispatch = createEventDispatcher()

  //when it's time to trigger the event
  dispatch('eventName')
</script>

Now other components can use ours using

现在其他组件可以使用我们的

<ComponentName on:eventName={event => {
  //do something
}} />

You can also pass an object to the event, passing a second parameter to dispatch():

您还可以将对象传递给事件,将第二个参数传递给dispatch()

<script>
  import { createEventDispatcher } from 'svelte'
  const dispatch = createEventDispatcher()
  const value = 'something'

  //when it's time to trigger the event
  dispatch('eventName', value)

  //or

  dispatch('eventName', {
    someProperty: value
  })
</script>

the object passed by dispatch() is available on the event object.

dispatch()传递的对象在event对象上可用。

我们从这里去哪里 (Where Do We Go From Here)

I hope this little handbook was useful to shine a light on what Svelte can do for you, and I hope you are now interested to learn more about it!

我希望这本小手册对阐明Svelte可以为您提供的服务很有帮助,并且希望您现在有兴趣进一步了解它!

I can now point you to two places to learn more:

我现在可以将您指向两个地方以了解更多信息:

That's it!

而已!

I can point you to my website flaviocopes.com if you are interested in learning more. I publish one new tutorial every day and I'll be posting more Svelte guides soon!

如果您有兴趣了解更多信息,我可以将您指向我的网站flaviocopes.com 。 我每天都会发布一个新教程,并且很快就会发布更多Svelte指南!

Note: you can download a PDF / ePub / Mobi version of this book so you can read it offline.

注意:您可以下载本书的PDF / ePub / Mobi版本,以便离线阅读。

翻译自: https://www.freecodecamp.org/news/the-svelte-handbook/

苗条的生成树

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值