The directory structure

  • Said in the previous
  • About the Virtual DOM
  • What do industry heavyhitters think of Svelte
  • About the UI
  • Svelte and other frameworks
    • Start packing
    • Compare the size
    • Performance appraisal
    • Compare the performance
  • Use the Svelte template
  • Download the dependent
  • Start the project
  • Open the page
  • Install the UI
  • Understand grammar briefly
    • Data binding
    • Conditions apply colours to a drawing
    • Render loop
    • event
    • component
      • The value of
    • animation
    • The life cycle
  • case
  • annotations
  • reference

Said in the previous

I don’t know if you know svelte. Recently, I happened to read an article titled “It’s almost 2020, You haven’t heard of SvelteJS?” [0], comparing Svelte with other frameworks

Svelte Chinese doc [1]

Compare the dimensions of projects developed for each framework

Compare the performance scores of Lighthouse projects

I was a little surprised to be honest. Are you serious?

So I hold a try and try mentality to be a reviewer

About the Virtual DOM

Rich Harris, author of Svelte, points out in an article called “Virtual DOM Is Pure Overhead” [2] why not use the virtual DOM

The three steps of the virtual DOM

  1. Both snapshots contain one element. In both cases<div>, which means we can keep the same DOM nodes
  2. We enumerate all the properties on the old and new properties,<div>To see if any properties need to be changed, added or removed. In both cases, we have a property – AclassNameThe value of"greeting"
  3. Descending into the element, we see that the text has changed, so we need to update the real DOM

Svelte skips the first two steps and executes the third step

if (changed.name) {
  text.data = name;
}
Copy the code

This is pretty much the update code generated by Svelte. Unlike traditional UI frameworks, Svelte is a compiler that knows how things are changing in the application at build time, rather than waiting to work at run time.

What do industry heavyhitters think of Svelte

You Yuxi, the author of VUE, answered the question “What do you think of Svelte as a front-end framework” on Zhihu. [3]

“The core idea of Svelte is to reduce the amount of framework runtime code by static compilation.”

About the UI

I think these two UIs are pretty good

Material UI

sveltematerialui.com/

Github.com/hperrin/sve…

SVELTESTRAP

sveltestrap.js.org/

Github.com/bestguy/sve…

Svelte and other frameworks

In his spare time, Mr. Yan found a repository called Realworld that had 24 conduits implementing As, which is for comparing performance and size;

Vue/React /svelte

  • Compress the package size after the project is packaged
  • Project web page performance analysis and comparison

Vue:github.com/gothinkster…

React:github.com/gothinkster…

Svelte:github.com/sveltejs/re…

Interested students can also take a look at other frameworks github.com/gothinkster…

Start packing

For these three projects, the packing sequence is basically the same time to execute the NPM run build, svelte directly in the blink of an eye I finished the package, snap very fast (a little exaggeration ~ a few seconds)

After waiting for vue and React to be packaged at the same time, I started to compress static files in a unified ZIP format

Compare the size

Rank the following

  1. Svelte 89.9 KB
  2. Vue – 483 KB
  3. The react – 490 KB

As expected the gap is really as scary as legend

Performance appraisal

Yan used Lighthouse (Google’s Web performance analytics tool) in Chrome to compare performance scores

Global Installation of Lighthouse

npm install -g lighthouse
Copy the code

Execute (directly use the corresponding online address)

lighthouse https://realworld.svelte.dev/
Copy the code

This is a screenshot of what I tested below

vue

react

svelte

Compare the performance

The performance score is ranked as follows:

  1. Svelte – 83.
  2. The react – 52
  3. Vue – 32

Svelte also held on to the top spot as expected

Use the Svelte template

See above, every day is forced to do performance optimization of the students, excited ~ then let’s learn a simple performance of the powerful svelte

Svelte template [4], we directly use a template to start

git clone https://github.com/sveltejs/template
&
cd template-master
Copy the code

Download the dependent

yarn install 
or 
npm install
Copy the code

After downloading, let’s look at the table of contents. Lao Yan’s evaluation is simplicity

Start the project

yarn dev
or
npm run dev
Copy the code

After the startup is complete

Your application is ready~! � -local: http://localhost:5000 - Network: Add '--host' to exposeCopy the code

Open the page

Enter http://localhost:5000 in the address bar

We can see a page like hello World

Install the UI

Here we use sveltestrap

npm install --save sveltestrap 
npm install --save bootstrap
Copy the code

Introduced in main.js

import 'bootstrap/dist/css/bootstrap.min.css';
Copy the code

Introduce components into the page

<script>
	import { Button } from "sveltestrap";
	const handleClick = () = > alert("I warned you!");
</script>

<Button color="danger" on:click={handleClick}>Do Not Press</Button>
Copy the code

Understand grammar briefly

I think it is necessary to have a brief understanding of its grammar before studying it

Data binding

In Vue, our variables need to be written in data, whereas svelte syntax is more native

<! -- vue -->
data() {
	return {
		name: 'hhh',
	};
}

<div>{{name}}</div>
Copy the code

Svelte binding data, svelte dynamic binding requires {}

<script>
	import { Button } from "sveltestrap";
	// Define data
	let name = "hhh";
	let src = 'http://crazy-x-lovemysoul-x-vip.img.abc188.com/images/logo.png';
</script>
<! -- Bind data -->
<! -- if kv is consistent, just write one -->
<img {src} alt="">
<Button>{name}</Button>
Copy the code

Conditions apply colours to a drawing

Vue has conditional rendering v-if V-else -if V-else,svelte also has it

<script>
	let condition = 1;
</script>
{#if condition == 2}
	<p>sad</p>
{:else if condition == 1}
	<p>injury</p>
{:else if condition == 0}
	<p>day</p>
{:else}
	<p>remember</p>
{/if}
Copy the code

Render loop

Loop render list

<script>
    // Define variables
	let news = [
        { id: 1.title: 'Biden calls for an end to treating opponents like enemies.' },
        { id: 2.title: 'Verdict in first trial of Jiangsu Xiangshui Bombing that Killed 78' },
        { id: 3.title: 'Chang 'e-5 will make a soft landing on the moon.'}];</script>


<ul>
    <! -- Do you have any sense of EJS -->
	{#each news as {title}}
		<li>
			<a href="https://www.baidu.com/s?rsv_idx=1&wd={title}">
				{title}
			</a>
		</li>
	{/each}
</ul>


<style>
	ul.li{
		list-style: none;
	}
	a{
		color: #ff3e00;
	}
</style>
Copy the code

How does it feel like ejS loop rendering [5]?

event

In svelte method directly write function definition function can be used

<script>
	import { Button } from "sveltestrap";
	// Define data
	let name = "hhh",title = 'title';
	// Define the method
	const handleClick = () = > {
		name = "Yan Lao Shi"
		title = "Old Yan takes you to the pit, Svelte."
	};
</script>
<! -- on:click bind method {bind dynamic value}-->
<Button color="danger" on:click={handleClick}>{name}</Button>
<h1>{title}</h1>
Copy the code

component

Components are an essential feature of the framework

How about creating a component in Svelte

app.svelte

<script>
    // Import components directly to use without registration
	import Child from './components/child.svelte'
	let name = 'I am your father'
</script>

<div>
	{name}
	<Child></Child>
</div>
Copy the code

Create a child.svelte page

<script>
    let title = 'I am your son.'
</script>

<div>{title}</div>
Copy the code

Now that we have the component, let’s look at the component pass.

The value of

app.svelte

<script>
	import Child from './components/child.svelte'
	let name = 'I am your father'
	let childName = "The dog left"
</script>

<div>
	{name}
	<Child {childName} ></Child>
</div>
Copy the code

child.svelte

<script>
    export let childName;
</script>

<div>Dad gave me the name {childName}</div>
Copy the code

We just had a simple single pass

So let’s try passing an object

app.svelte

<script>
	import Child from './components/child.svelte'
	let name = 'I am your father'
	let aboutMe = {
		name:'the dog left'.age:18.gender:'man'
	}
</script>

<div>
	{name}
    <! - through... A aboutMe -- -- >
	<Child {. aboutMe} ></Child>
</div>
Copy the code

child.svelte

<script>
    export let name,gender,age;
</script>

<div>I'm going to call it {name}</div>
<div>I took the age {age}</div>
<div>I took the gender {gender}</div>
Copy the code

How much effort is it going to take? You need to receive them one by one. There is a saying that existence is reasonable

animation

The official API mentions that Svelte provides some animation effects for you to use

Let’s go straight to the official example fade-in animation

<script>
	import { fade } from 'svelte/transition';
	let visible = true;
</script>

<label>
	<input type="checkbox" bind:checked={visible}>
	visible
</label>

{#if visible}
	<p transition:fade>
		Fades in and out
	</p>
{/if}
Copy the code

The life cycle

The life cycles in svelte are onMount, beforeUpdate, afterUpdate, afterUpdate and the following are listed in order for the big guys

  • OnMount (after mounting)

This onMount function is executed as a callback immediately after component is mounted into the DOM. It must be called during Component initialization (but does not have to be inside the Component; It can be called from an external module).

<script>
    import { onMount } from 'svelte';

    onMount(() = > {
        console.log('the component has mounted');
    });
</script>
Copy the code

If onMount is required to return a function, it is called when component is unmounted.

<script>
	import { onMount } from 'svelte';

	onMount(() = > {
		const interval = setInterval(() = > {
			console.log('beep');
		}, 1000);

		return () = > clearInterval(interval);
	});
</script>
Copy the code
  • BeforeUpdate (beforeUpdate)

BeforeUpdate The callback function runs immediately after any state change before the component is updated. The first callback will be before the initial onMount.

<script>
    import { beforeUpdate } from 'svelte';

    beforeUpdate(() = > {
        console.log('the component is about to update');
    });
</script>
Copy the code
  • afterUpdate

AfterUpdate runs a callback immediately after a component is updated

<script>
    import { afterUpdate } from 'svelte';

    afterUpdate(() = > {
        console.log('the component just updated');
    });
</script>
Copy the code
  • OnDestroy (after destroy)

Run the callback after the component is unloaded. Among onMount, beforeUpdate, afterUpdate, and onDestroy, this is the only component that runs in a server-side component. 4

<script>
    import { onDestroy } from 'svelte';

    onDestroy(() = > {
        console.log('the component is being destroyed');
    });
</script>
Copy the code

case

Lao Yan was wandering around and happened to see an official sample of the to do List. I thought I would show you how to do it, but since there is a ready-made one, I will do it

There is no framework that you can’t learn by writing a Todolist

Since there is too much style code, let’s show the renderings first and then look at the code

<script>
	import { quintOut } from 'svelte/easing';
	import { crossfade } from 'svelte/transition';
	import { flip } from 'svelte/animate';
	/ / animation
	const [send, receive] = crossfade({
		duration: d= > Math.sqrt(d * 200),

		fallback(node, params) {
			const style = getComputedStyle(node);
			const transform = style.transform === 'none' ? ' ' : style.transform;
			return {
				duration: 600.easing: quintOut,
				css: t= > `
					transform: ${transform} scale(${t});
					opacity: ${t}
				`}; }});let uid = 1;
	// Default data
	let todos = [
		{ id: uid++, done: false.description: 'write some docs' },
		{ id: uid++, done: false.description: 'start writing blog post' },
		{ id: uid++, done: true.description: 'buy some milk' },
		{ id: uid++, done: false.description: 'mow the lawn' },
		{ id: uid++, done: false.description: 'feed the turtle' },
		{ id: uid++, done: false.description: 'fix some bugs'},];// Add todo
	function add(input) {
		const todo = {
			id: uid++,
			done: false.description: input.value
		};

		todos = [todo, ...todos];
		input.value = ' ';
	}
	// Delete method
	function remove(todo) {
		todos = todos.filter(t= >t ! == todo); }// Select the method
	function mark(todo, done) {
		todo.done = done;
		remove(todo);
		todos = todos.concat(todo);
	}
</script>

<div class='board'>
    <! -- Hit Enter to add -->
	<input
		placeholder="what needs to be done?"
		on:keydown={e= > e.which === 13 && add(e.target)}
	>
	<! -- -- -- > agents
	<div class='left'>
		<h2>todo</h2>{#each todos.filter(t => ! t.done) as todo (todo.id)}<label
				in:receive="{{key: todo.id}}"
				out:send="{{key: todo.id}}"
				animate:flip
			>
				<! Select 'done' -->
				<input type=checkbox on:change={()= > mark(todo, true)}>
				{todo.description}
				<! - delete - >
				<button on:click="{() => remove(todo)}">remove</button>
			</label>
		{/each}
	</div>
	<! -- Completed -->
	<div class='right'>
		<h2>done</h2>
		{#each todos.filter(t => t.done) as todo (todo.id)}
			<label
				class="done"
				in:receive="{{key: todo.id}}"
				out:send="{{key: todo.id}}"
				animate:flip
			>
				<! -- Change status to agent -->
				<input type=checkbox checked on:change={()= > mark(todo, false)}>
				{todo.description}
				<! - delete - >
				<button on:click="{() => remove(todo)}">remove</button>
			</label>
		{/each}
	</div>
</div>

<style>
	.board {
		display: grid;
		grid-template-columns: 1fr 1fr;
		grid-gap: 1em;
		max-width: 36em;
		margin: 0 auto;
	}

	.board > input {
		font-size: 1.4 em;
		grid-column: 1/3;
	}

	h2 {
		font-size: 2em;
		font-weight: 200;
		user-select: none;
		margin: 0 0 0.5 em 0;
	}

	label {
		position: relative;
		line-height: 1.2;
		padding: 0.5 em 2.5 em 0.5 em 2em;
		margin: 0 0 0.5 em 0;
		border-radius: 2px;
		user-select: none;
		border: 1px solid hsl(240.8%.70%);
		background-color:hsl(240.8%.93%);
		color: # 333;
	}

	input[type="checkbox"] {
		position: absolute;
		left: 0.5 em;
		top: 0.6 em;
		margin: 0;
	}

	.done {
		border: 1px solid hsl(240.8%.90%);
		background-color:hsl(240.8%.98%);
	}

	button {
		position: absolute;
		top: 0;
		right: 0.2 em;
		width: 2em;
		height: 100%;
		background: no-repeat 50% 50% url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%23676778' D ='M12, 2c17.53,22,6.47 22,12C22,17.53 17.53,22 12,22C6.47,22 2,17.53,12C2,6.47 6.47,2 M17 12, 2, 7 h14. 5 l13. 5 or 6 H10.5 L9.5, 7 h7v9h17v7m9, 18 h15a1, 16 or 17 V10H8V17A1 1 0 0, 0, 1, 0, 0, 0 9, 18 '% 3 e % 3 c/Z path % 3 e % 3 c/SVG % 3 e");
		background-size: 1.4 em 1.4 em;
		border: none;
		opacity: 0;
		transition: opacity 0.2 s;
		text-indent: -9999px;
		cursor: pointer;
	}

	label:hover button {
		opacity: 1;
	}
</style>
Copy the code

When you can write this todolist manually, you have already started, because that’s all Yan can do

Finally, I submitted the code to Git for you to download

git clone [email protected]:CrazyMrYan/study-svelte.git
Copy the code

annotations

[0] zhuanlan.zhihu.com/p/97825481

[1] www.firecat.run/

[2] svelte. Dev/blog/virtua…

[3] www.zhihu.com/question/53…

[4] github.com/sveltejs/te…

[5] ejs.bootcss.com/#docs

reference

  • www.firecat.run/docs
  • zhuanlan.zhihu.com/p/97825481
  • Iiong.com/sveltejs-st…