It’s written by Rich Harris, author of Ractive, Rollup, and Buble

And now new wheels! The FRAMEWORK’s API design is inherited from Ractive (which is also very similar to Vue, naturally), but that’s not the point.

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

For example, the current frameworks, whether React Angular or Vue, no matter how you compile them, always need to “import” the framework itself, known as the Runtime.

But with Svelte, when a Svelte component is compiled, all the runtime code is included in it. You don’t need to introduce a so-called framework runtime in addition to the component itself! Of course, this doesn’t mean that Svelte doesn’t have a runtime, but the cost can be small for two reasons:


One obvious difference with Svelte, which surprised me, is that it uses a real DOM, not a virtual DOM

Is the front frame a circle?

Round and round again

So according to the official website guide, plus their own translation understanding, wrote a pit guide

Here is a translation of the official guide

At the same time, I wrote the above cases by myself and ran

Personally, I think the official document arrangement is gradual, from the shallow to the deep, I hope we gradually understand the framework

Engineering use

There are two ways to use the Svelte website

Here I use the first one, in this address svelte.dev/repl/hello-… Download an off-the-shelf project directly

The root directory is displayed

cd svelte-app
npm install

Copy the code

This is the default project content downloaded from the Svelte website

Then run

npm run dev

Copy the code

After running, the listener listens to port 5000 by default

Open the editor and go to the SRC directory. There is a default app.svelte file that looks like this

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

<h1>Hello {name}!</h1>
Copy the code

The browser works as follows


The basic grammar

The files in svelte are created with the filename.svelte

The JS code for a.svelte file needs to be in the script tag, the styles in the style tag, and the HTML structure is independent of both


<script>

</script>

<div>


</div>


<style>


<style/>

Copy the code

Use of variables

Variables need to be wrapped in {}, and statements and expressions can be used inside


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


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

<h1>Hello {name.toUpperCase()}!</h1>
Copy the code

Use of styles

CSS styles need to be written in the style tag

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

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

<style>
 h1{
    color:# 777
 }
</style>


Copy the code

Dynamic properties

Similar to Vue’s V-bind, dynamic binding is also possible for attributes of tags

<script>
	let src = 'tutorial/image.gif';
	let name = 'Rick Astley';
</script>

<img src={src} alt="{name} dances.">
Copy the code

Of course, svelte also provides syntactic sugar, which can be used when attribute names are the same as variable names

<img {src} alt="{name} dances.">
Copy the code

componentization

Svelte can also use. Svelte files as subcomponents

Create a new child.svelte file in the Components folder and import it in app.svelte

Child.svelte

<p>This is another paragraph.</p>

Copy the code

App.svelte

<script>
	import Child from './components/Child.svelte';
</script>

<p>This is a paragraph.</p>
<Child/>

<style>
	p {
		color: purple;
		font-family: 'Comic Sans MS', cursive;
		font-size: 2em;
	}
</style>

Copy the code

Results the following

Reactivity of reactive

Svelte’s core system is “reactivity,” which keeps the DOM in sync with the state of your application

The click event of a button is used here to demonstrate reactivity

<script>
	let count = 0;

    // Define an accumulation function
	function incrementCount() {
		count += 1;
	}
</script>


// Svelte event binding, which will be covered later

<button on:click={incrementCount}>{count} times}</button>
Copy the code

Click the button “+1” and the DOM will be updated synchronously

Declarations statement

Svelte automatically updates the DOM when a component’s state changes.

Sometimes, however, certain states of a component need to be calculated against other states, such as the full name based on the first and last names

In this case, we can use the reactive declarations

Define a declaration using $:


<script>

let firstName="Simon"
let lastName="Snow"

$:fullName=firstName+lastName

</script>


<p>Full name is {fullName}</p> // Simon blows snow

Copy the code

$: This looks strange, not js code, but is similar to the Watch and computed properties in Vue

Svelte will interpret $: as “reruns this code if any of the referenced values change.”

Therefore, fullName is automatically updated when either the last name or the fullName is changed

In fact, we can use it directly in the DOM

<p>{firstName+lastName}</p>

Copy the code

Instead of a statement

But when we use declarations a lot, like calculating multiples of a number frequently

<script>
	let count = 0;
	$: doubled = count * 2;

</script>

<p>{count} = {count}</p>

Copy the code

At this point, the declaration is much more convenient.

In addition, the declaration can be any statement. For example, we can record the value of count when it changes:

You can use conditions and common output statements

$: console.log(`the count is ${count}`);

$: {
	console.log(`the count is ${count}`);
	alert(`I SAID THE COUNT IS ${count}`);
}
Copy the code

It could even be a conditional judgment

<script>
	let count = 0;

	$: if (count >= 10) {
		alert(The current value is too large);
		console.log(`the count is ${count}`);
		count = 9;
	}

	function handleClick() {
		count += 1;
	}
</script>

<button on:click={handleClick}>Ordered {count}</button>
Copy the code

Update array and object values

Because the reactivity of Svelte is triggered by assignment, using array methods such as push and splice does not automatically result in updates.

For example, in the following one, we click make the array length +1, but it doesn’t change anything

<div>

  <button on:click={addArr}>The length of the array is increased by 1</button>
  <p>The length of arR is {arr.length}</p>

</div>

<script>

  let arr=[1.2.3.4]

  function addArr(){
    arr.push(arr.length+1)}</script>

Copy the code

The solution is to reassign

function addArr(){
    arr[arr.length]=arr.length+1
 }
 
Copy the code

For simplicity, use ES6’s extension operator

function addArr(){
   arr=[...arr, arr.length+1]
 }
Copy the code

Here’s a simple formula: The name of the update variable must appear to the left of the assignment.

The Props component passes a value

In any real-world application, data needs to be passed down from one component to its children. To do this, we need to declare the property, usually abbreviated as “props.”

In Svelte, we declare an props using the export keyword

Create a new child.svelte

<div>
    <h3>Pass the name: {propsName}</h3>
    <p>{propsConfig.name}</p>
    <p>{propsConfig.age}</p>
    <p>{propsConfig.male}</p>
</div>

<script>
  // Declare props with a default value of type string
  export let propsName="zds"
  
  // Declare an props that has no default value
  export let propsConfig;

</script>

Copy the code

Then refer to it in app.svelte and pass the value

<script>

  import Child from "./component/Child.svelte"
  
  let name="Pikachu"
  let config={
		name:"svelte".age:5.sex:"male"
	}

</script>

<div>
    <Child propsName={name}  propsConfig={config}/>    
</div>

Copy the code

When there are too many props in a child component, for example

Info.sveltr

<script>
  export let name
  export let age
  export let sex
  export let phone
  export let address

</script>
Copy the code

You can use the extension operator when passing values…

<script>
  import Info from "./component/Info.svelte"
  
  let infos={
      name:"Pikachu".age:22.sex:"male".phone:"0225-78737".address:"Suzhou, Jiangsu"
  }

</script>

<Info {. infos} / >

Copy the code

Just make sure that the attribute name of the passed object is the same as the props name that the child component exposes


Continue to be updated July 9, 2021 at 16:46:16