当前位置:网站首页>Svelte official introductory tutorial (1) - Introduction
Svelte official introductory tutorial (1) - Introduction
2022-07-16 05:28:00 【Jason show】
Introducing Svelte Before , The first priority is :
Svelte No Servlet,Svelte It's a front end Web frame , and Java Servlet And Svelte Not a type of program , Be sure to draw a clear lesson .
If you enter by mistake , Please go out and turn right .
One 、 A glimpse of the door
The flower path has never been swept by a guest , This tutorial is just for you .
This tutorial is gradual , Teach you how to use Svelte Easily create fast and small applications .
If you want to go deep into the details , Explore thoroughly , You might as well read it at any time API file And Example .
If you can't wait to develop on this computer now ,60 Get started in seconds Just for you .
All examples in this tutorial can be tested online , You don't need to create any projects or install software packages in the learning process , Click the link below to enter REPL, You can watch the tutorial , Edge practice :
1. What is? Svelte?
Svelte For building fast Web application .
Svelte similar React and Vue, Are committed to making it easy for you to build a flexible and interactive user interface .
Unlike them :Svelte At build time Turn your code into better JavaScript, Not in Runtime Just explain and execute your code .
This indicates that you don't have to pay the performance cost of the framework itself , And there is no additional performance loss when loading for the first time .
You can use Svelte Write the whole application , It can also be used to gradually refactor existing code , The whole half is ok ; You can also output only a single independent component ( There is no need to force the framework itself ) And use it in any frame , It can be described as exquisite .
2. How to use this tutorial ?
First , At least you are right HTML、CSS and JavaScript Have a preliminary understanding , Otherwise, the learning process will be like a sea of smoke , At a loss .
Please follow the carefully planned steps of this tutorial step by step , When introducing new knowledge in each section , Will be accompanied by a small exercise . The study of all chapters is a link between the past and the future , Don't jump reading wantonly .
3. Understanding components
One Svelte An application consists of one or more components (Components) It's a combination of .
Each component corresponds to a reusable .svelte file , Containing components HTML、CSS and JavaScript All the code .
The following is the simplest component :
<h1>Hello world!</h1>
Two 、 Add data
Components that only present some labels feel boring , We try to add some data .
First , Add a script label , And declare a name Variable :
<script> let name = 'world'; </script>
<h1>Hello world!</h1>
then , You can use this in the tag name Variable :
<h1>Hello {name}!</h1>
In curly brackets , We can write any JavaScript.
You can then try the following name Change it to name.toUpperCase(), This greeting seems more intense .
Be careful : What you seem to create is a global variable , actually ,name It is still limited to local variables of components , in other words , You cannot create global objects (Window) Access to name Variable .
3、 ... and 、 Dynamic properties
Curly braces can control text except , It also applies to the attributes of elements . Take the following code for example :
<script> let src = 'tutorial/image.gif'; </script>
<img>
The picture tag below is missing src Property Properties , Now try it :
<img src={src}>
A profound , begin to display one 's talent .
however Svelte stay build Still give a warning :
A11y: <img> element should have an alt attribute
According to the warning ,img The element should be added alt attribute .
The purpose of this action is to expect your application to expand the audience as much as possible , Take into account the whole people , Including poor eyesight 、 Dyskinesia 、 People with low-end hardware or slow network speed .
Accessibility (Accessibility, abbreviation a11y) It often takes time and effort , If you write tags that violate accessibility ,Svelte Will remind you through warning .
under these circumstances , We lack the ability to describe images for users using screen readers alt attribute , Or the network connection is slow or unstable 、 Unable to download user description image of image . Let's add a :
<img src={src} alt="A man dances.">
We can do it in Within the properties Use curly braces .
Try changing it to "{name} dances.", Remember in <script> The label states name Variable .
Attribute abbreviation
Attributes with the same name and value are not uncommon , for example src={src}.
Svelte It provides us with a convenient shorthand abbreviation for this situation :
<img {src} alt="A man dances.">
Four 、 style
As in the HTML In the same , You can add <style> Mark .
<style> /* The style is written here */ </style>
<p> This is a passage .</p>
Let's make
Add some styles to the element :
App.svlete
<style> p {
color: purple; font-family: 'Comic Sans MS', cursive; font-size: 2em; } </style>
<p> This is a passage .</p>
It is important to , The rules are “ Components within the scope ”. You won't accidentally change elsewhere in the application <p> Style of element , As we will see in the next step .
5、 ... and 、 Nested components
It is impractical to put the entire application in one component . In its place , We can import components from other files , And include them like elements .
Here's our App.svelte Components
<style> p {
color: purple; font-family: 'Comic Sans MS', cursive; font-size: 2em; } </style>
<p>This is a paragraph.</p>
Let's write one first Nested Components :
Nested.svelte
<p>This is another paragraph.</p>
next , We are App.svelte Add a <script> Mark and import Nested.svelte…
<script> import Nested from './Nested.svelte'; </script>
… Then you can use it in your code :
<p> This is a paragraph .</p>
<Nested/>
Please note that , Even if Nested.svelte have <p> Elements ,App.svelte The style of is not affected .
Attention, please. , Component name Nested The initial is in capital . This Convention is adopted to enable us to distinguish between user-defined components and conventional HTML label .
6、 ... and 、HTML label
Usually , The string is inserted as plain text , It means something like < and > Such characters have no special meaning .
But sometimes you need to directly HTML Render to components . for example , The word you are reading now exists in markdown In file , This document HTML The form of is included in this page :
<script> let string = `this string contains some <strong>HTML!!!</strong>`; </script>
<p>{string}</p>
Svelte You can use special labels in {@html ...} To solve this problem :
<p>{@html string}</p>
Svelte Will not insert into DOM Right before the middle
{@html ...}Any cleanup of expressions in . let me put it another way , If you use this function , What matters is , You must manually escape HTML, Otherwise, the user will suffer XSS Risk of attack .
7、 ... and 、 Create a App
This tutorial is designed to familiarize you with the process of writing components . But sometimes , You will want to start writing components in your text editor .
First , You need to Svelte Integrated with build tools . Targeted Rollup and webpack Officially maintained plug-ins for …
- rollup-plugin-svelte
- svelte-loader
… And all kinds of reasons Community maintenance Plug in for .
If you are Web New to development , And I haven't used these tools before , Please don't worry . We have prepared a ordinary Svelte guide , It will guide you through the whole process .
You also need to configure a text editor . If you are using VS Code, Please install Svelte Extension , Otherwise, please follow This guide The description of configures the text editor to .svelte File with the .html identical , To highlight syntax .
then , Once the project is established , It's easy to use Svelte Components . The compiler makes every component regular JavaScript class - Just import and use new Instantiate :
import App from './App.svelte';
const app = new App({
target: document.body,
props: {
// We will learn later props
answer: 42
}
});
then , You can use it on demand Components API And app Interact .
8、 ... and 、 debugging
occasionally , It is useful to check the data flowing through the application .
One solution is to use console.log(...). however , If you want to pause , You can use {@debug ...} Tags are used with a comma separated list of values to check :
App.svelte
<script> let user = {
firstname: 'Ada', lastname: 'Lovelace' }; </script>
{@debug user}
<h1>Hello {user.firstname}!</h1>
If you open it now devtools And prepare to work with <input> Elements interact , Will be in user The debugger is triggered when its value is modified .
summary
This chapter has briefly introduced Svelte The basic usage of ,Svelte Although with React、Vue equally , Strive to build the front end Web Applications ,Svelte For the best performance and the simplest code output , The compiler is used to directly generate the final code .
Svelte And Vue Of SFC More similar , That is, a file represents a component .
Except under special circumstances ( Back 《 modular 》 This chapter will explain in detail ), Otherwise, the top floor HTML Only one is allowed script label ( other script It can be placed in child elements , But the result is different ), One style label ( other style Labels can be placed in sub elements , But the result is different ).
We want to add a variable similar to two-way binding , Just as usual , Declare a common variable .
And copy the relevant attributes to the element , Then with React、Vue Very close to .
Styles are locally scoped by default , Styles within components , It will not affect other components .
Last ,Svelte Components of can be directly output as native JavaScript object , You can easily put this object in React、Vue Or import from other places , And then through new Instantiation , You can use .
边栏推荐
- XML introduction
- ES6--let与const
- Random signal analysis, 2nd Edition [edited by Zhao Shuqing and Zheng Wei] (part) answer to homework after class (written by myself)
- 41.js--闭包
- [tensorflow2] attributeerror: 'tensor' object has no attribute 'numpy' solution (tf.py_function)
- 正则表达式
- Range installation and attacker configuration for penetration testing
- sql_server2014下载与安装
- dva数据流
- 【黄啊码】PHP配合xlswriter实现无限表头层级Excel导出
猜你喜欢

SNMP起步啦

vue+axios+mysql实现分页查询,条件查询以及批量删除

微信红包项目测试小结

Advanced architects, 16 common principles of microservice design and Governance

Range installation and attacker configuration for penetration testing

初识c语言(一)

Idea automatically exports SQL statements of tables in the database

MVN clean or MVN clean package did not detect the test file

ES6--let与const

(cvpr-2022) Lagrangian motion analysis and perspective embedding for improved gait recognition
随机推荐
39.js--作用域
Svelte 官方入门教程(2)—— 反应性
[tensorflow2] implementation of gradient inversion layer (GRL) and domain antagonism training neural network (Dann)
XML介绍
藍橋杯單片機第13届省賽題
A grayscale interface migration scheme
<statement> or DELIMITER expected, got ‘id‘
Oil monkey script changes TW style
Idea automatically exports SQL statements of tables in the database
JS中Math对象
Oracle数据库 错误代码解决办法
扩展知识——JS的劫持技术
2.内存泄漏与内存溢出
Summary of wechat red envelope project test
Micro service mode: sidecar
【黄啊码】今天居然有人问我:where 1=1 是什么意思?
js--笔试题(集)
Range installation and attacker configuration for penetration testing
【黄啊码】fastadmin接入微信支付和支付宝支付
Svelte 官方入门教程(1)—— 简介