Svelte之基础知识一

2024-03-10 16:52
文章标签 基础知识 svelte

本文主要是介绍Svelte之基础知识一,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 参考资料
  • 什么是Svelte?
  • 简介
    • 添加数据`{}`
    • 动态属性`{}`
    • 嵌套组件
    • HTML标签`@html`
    • 创建一个应用程序
  • 反应性能力
    • 赋值`on:click={}`
    • 声明`$:`
    • 语句`$:{}`
    • 更新数组和对象
  • 属性
    • Declaring props`export`
    • 属性对象传递`{...xxx}`
  • 逻辑
    • if语句`{#if xxx}...{/if}`
    • else语句`{#if xxx}...{:else}...{/if}`
    • else-if语句`{#if xxx}...{:else if xxx}...{:else}...{/if}`
    • each语句`{#each xxx as xx}...{/each}`
    • 为each语句添加key值`{#each xxx as xx(key-xxx)}...{/each}`
    • await语句`{#await xxx}...{:then xxx}...{:catch error}...{/await}`
  • 事件
    • DOM 事件`on:xxx={xxx}`
    • inline handlers
    • 事件修饰器`on:xxx|once`
    • 组件事件
    • 事件转发`on:message`、`on:click`

参考资料

  • 官网-中文

什么是Svelte?

  • Svelte 是一个构建 web 应用程序的工具
  • Svelte 与诸如 React 和 Vue 等 JavaScript 框架类似,都怀揣着一颗让构建交互式用户界面变得更容易的心。
    但是有一个关键的区别:Svelte 在 构建/编译阶段 将你的应用程序转换为理想的 JavaScript 应用,而不是在 运行阶段 解释应用程序的代码。这意味着你不需要为框架所消耗的性能付出成本,并且在应用程序首次加载时没有额外损失。
    你可以使用 Svelte 构建整个应用程序,也可以逐步将其融合到现有的代码中。你还可以将组件作为独立的包(package)交付到任何地方,并且不会有传统框架所带来的额外开销。

简介

添加数据{}

<script>let name = 'world';
</script><h1>Hello {name}!</h1>

对比Vue:{{}} => {}

动态属性{}

<script>let src = 'tutorial/image.gif';let name = 'Rick Astley';
</script><img {src} alt="{name} dances.">

对比Vue::src = "" => src={}

嵌套组件

注意:组件名称 Nested 的首字母大写。采用此约定是为了使我们能够区分用户自定义的组件和一般的 HTML 标签。

<script>import Nested from './Nested.svelte';
</script><style>p {color: purple;font-family: 'Comic Sans MS', cursive;font-size: 2em;}
</style><p>This is a paragraph.</p>
<Nested/>

HTML标签@html

<script>let string = `this string contains some <strong>HTML!!!</strong>`;
</script><p>{@html string}</p>

对比Vue:v-html => @html

创建一个应用程序

  • VS Code安装插件:Svelte扩展

反应性能力

赋值on:click={}

<script>let count = 0;function handleClick() {count++;// event handler code goes here}
</script><button on:click={handleClick}>Clicked {count} {count === 1 ? 'time' : 'times'}
</button>

对比Vue:@click="" => on:click={}

声明$:

<script>let count = 0;$: doubled = count * 2function handleClick() {count += 1;}
</script><button on:click={handleClick}>Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
<p>{count} doubled is {doubled}
</p>

对比Vue:computed => $:

语句$:{}

<script>let count = 0;$: console.log(`the count is ${count}`)$: {console.log(`the count is ${count}`)alert(`the count is ${count}`)}$: if (count >= 2){console.log(`the count is ${count}`)alert(`count is dangerously high ${count}`)}function handleClick() {count += 1;}
</script><button on:click={handleClick}>Clicked {count} {count === 1 ? 'time' : 'times'}
</button>

更新数组和对象

  • 由于 Svelte 的反应性是由赋值语句触发的,因此使用数组的诸如 push 和 splice 之类的方法就不会触发自动更新。
  • 解决该问题的一种方法是添加一个多余的赋值语句
  • 一个简单的经验法则是:被更新的变量的名称必须出现在赋值语句的左侧
	<script>let numbers = [1, 2, 3, 4];function addNumber() {numbers = [...numbers, numbers.length + 1]numbers[numbers.length] = numbers.length + 1;}const obj = {foo: {bar: 1}}const foo = obj.foo;foo.bar = 'baz';$: sum = numbers.reduce((t, n) => t + n, 0);</script><p>{numbers.join(' + ')} = {sum}</p><button on:click={addNumber}>Add a number</button><p>{obj.foo.bar}</p>

属性

Declaring propsexport

  • 用于父子组件传值
    子组件:
	<script>export let answer;</script><p>The answer is {answer}</p>

父组件:

	<script>import Nested from './Nested.svelte';</script><Nested answer={412122}/>

对比Vue:prop => export

属性对象传递{...xxx}

<script>import Info from './Info.svelte';const pkg = {name: 'svelte',version: 3,speed: 'blazing',website: 'https://svelte.dev'};
</script><Info {...pkg}/>

逻辑

if语句{#if xxx}...{/if}

<script>let user = { loggedIn: false };function toggle() {user.loggedIn = !user.loggedIn;}
</script>{#if user.loggedIn}
<button on:click={toggle}>Log out
</button>
{/if}
{#if !user.loggedIn}
<button on:click={toggle}>Log in
</button>
{/if}

对比vue:v-if=>{#if xxx}...{/if}

else语句{#if xxx}...{:else}...{/if}

<script>let user = { loggedIn: false };function toggle() {user.loggedIn = !user.loggedIn;}
</script>{#if user.loggedIn}<button on:click={toggle}>Log out</button>
{:else}<button on:click={toggle}>Log in</button>
{/if}

对比vue:v-if v-else=>{#if xxx}...{:else}...{/if}

else-if语句{#if xxx}...{:else if xxx}...{:else}...{/if}

<script>let x = 7;
</script>{#if x > 10}<p>{x} is greater than 10</p>
{:else if 5 > x}<p>{x} is less than 5</p>
{:else}<p>{x} is between 5 and 10</p>
{/if}

each语句{#each xxx as xx}...{/each}

<script>let cats = [{ id: 'J---aiyznGQ', name: 'Keyboard Cat' },{ id: 'z_AbfPXTKms', name: 'Maru' },{ id: 'OUtn3pvWmpg', name: 'Henri The Existential Cat' }];
</script><h1>The Famous Cats of YouTube</h1><ul><!-- open each block -->{#each cats as cat, i}<li><a target="_blank" href="https://www.youtube.com/watch?v={cat.id}">{i + 1}:{cat.name}</a></li>{/each}<!-- close each block -->
</ul>

对比vue:v-for=>{#each xxx as xx}...{/each}

为each语句添加key值{#each xxx as xx(key-xxx)}...{/each}

<script>import Thing from './Thing.svelte';let things = [{ id: 1, color: '#0d0887' },{ id: 2, color: '#6a00a8' },{ id: 3, color: '#b12a90' },{ id: 4, color: '#e16462' },{ id: 5, color: '#fca636' }];function handleClick() {things = things.slice(1);}
</script><button on:click={handleClick}>Remove first thing
</button>{#each things as thing (thing.id)}<Thing current={thing.color}/>
<span>{thing.id}</span>
{/each}

对比vue::key="key-xxx"=>{#each xxx as xx(key-xxx)}...{/each}

await语句{#await xxx}...{:then xxx}...{:catch error}...{/await}

<script>let promise = getRandomNumber();async function getRandomNumber() {const res = await fetch(`tutorial/random-number`);const text = await res.text();if (res.ok) {return text;} else {throw new Error(text);}}function handleClick() {promise = getRandomNumber();}
</script><button on:click={handleClick}>generate random number
</button><!-- 方法一:全面 -->
{#await promise}
<p>waiting</p>
{:then value}
<p>{value}
</p>
{:catch error}
<p>{error}
</p>
{/await}<!-- 方法二:省略 -->
{#await promise then value}
<p>{value}</p>
{/await}

事件

DOM 事件on:xxx={xxx}

<script>let m = { x: 0, y: 0 };function handleMousemove(event) {m.x = event.clientX;m.y = event.clientY;}
</script><style>div { width: 100%; height: 100%; }
</style><div on:mousemove={handleMousemove}>The mouse position is {m.x} x {m.y}
</div>

inline handlers

<script>let m = { x: 0, y: 0 };function handleMousemove(event) {m.x = event.clientX;m.y = event.clientY;}
</script><style>div { width: 100%; height: 100%; }
</style><div on:mousemove={e => m = {x: e.clientX, y: e.clientY}}>The mouse position is {m.x} x {m.y}
</div>

事件修饰器on:xxx|once

所有修饰符列表:

  • preventDefault :调用event.preventDefault() ,在运行处理程序之前调用。比如,对客户端表单处理有用。
  • stopPropagation :调用 event.stopPropagation(), 防止事件影响到下一个元素。
  • passive : 优化了对 touch/wheel 事件的滚动表现(Svelte 会在合适的地方自动添加滚动条)。
  • capture — 在 capture 阶段而不是bubbling 阶段触发事件处理程序 ()
  • once :运行一次事件处理程序后将其删除。
  • self — 仅当 event.target 是其本身时才执行。
	<script>function handleClick() {alert('clicked')}</script><button on:click|once={handleClick}>Click me</button>
  • 可以将修饰符组合在一起使用,例如:on:click|once|capture={...}

组件事件

  • 子组件:createEventDispatcher()(‘xxx’, param)
    createEventDispatcher 必须在首次实例化组件时调用它,—组件本身不支持如 setTimeout 之类的事件回调。 定义一个dispatch进行连接,进而把组件实例化。
	<script>import { createEventDispatcher } from 'svelte';// setup code goes hereconst dispatch = createEventDispatcher()function sayHello() {dispatch('message', {text: 'Hello zoey'})}</script><button on:click={sayHello}>Click to say hello zoey</button>
  • 父组件:on:xxx
	<script>import Inner from './Inner.svelte';function handleMessage(event) {alert(event.detail.text);}</script><Inner on:message={handleMessage}/>

事件转发on:messageon:click

message 没有赋予特定的值得情况下意味着转发所有massage事件:

<script>import Inner from './Inner.svelte';
</script><Inner on:message/>

这篇关于Svelte之基础知识一的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/794884

相关文章

linux-基础知识3

打包和压缩 zip 安装zip软件包 yum -y install zip unzip 压缩打包命令: zip -q -r -d -u 压缩包文件名 目录和文件名列表 -q:不显示命令执行过程-r:递归处理,打包各级子目录和文件-u:把文件增加/替换到压缩包中-d:从压缩包中删除指定的文件 解压:unzip 压缩包名 打包文件 把压缩包从服务器下载到本地 把压缩包上传到服务器(zip

计组基础知识

操作系统的特征 并发共享虚拟异步 操作系统的功能 1、资源分配,资源回收硬件资源 CPU、内存、硬盘、I/O设备。2、为应⽤程序提供服务操作系统将硬件资源的操作封装起来,提供相对统⼀的接⼝(系统调⽤)供开发者调⽤。3、管理应⽤程序即控制进程的⽣命周期:进程开始时的环境配置和资源分配、进程结束后的资源回收、进程调度等。4、操作系统内核的功能(1)进程调度能⼒: 管理进程、线

go基础知识归纳总结

无缓冲的 channel 和有缓冲的 channel 的区别? 在 Go 语言中,channel 是用来在 goroutines 之间传递数据的主要机制。它们有两种类型:无缓冲的 channel 和有缓冲的 channel。 无缓冲的 channel 行为:无缓冲的 channel 是一种同步的通信方式,发送和接收必须同时发生。如果一个 goroutine 试图通过无缓冲 channel

java常用面试题-基础知识分享

什么是Java? Java是一种高级编程语言,旨在提供跨平台的解决方案。它是一种面向对象的语言,具有简单、结构化、可移植、可靠、安全等特点。 Java的主要特点是什么? Java的主要特点包括: 简单性:Java的语法相对简单,易于学习和使用。面向对象:Java是一种完全面向对象的语言,支持封装、继承和多态。跨平台性:Java的程序可以在不同的操作系统上运行,称为"Write once,

关于回调函数和钩子函数基础知识的整理

回调函数:Callback Function 什么是回调函数? 首先做一个形象的比喻:   你有一个任务,但是有一部分你不会做,或者说不愿做,所以我来帮你做这部分,你做你其它的任务工作或者等着我的消息,但是当我完成的时候我要通知你我做好了,你可以用了,我怎么通知你呢?你给我一部手机,让我做完后给你打电话,我就打给你了,你拿到我的成果加到你的工作中,继续完成其它的工作.这就叫回叫,手机

有关机械硬盘的基础知识

1,机械硬盘的品牌   目前市场中常见的笔记本电脑的机械硬盘品牌主要有希捷、西部数据、三星等。   2,机械硬盘的容量   硬盘容量,即硬盘所能存储的最大数据量。虽然笔记本电脑硬盘的容量会因单位密度的提升而增加,不过和台式电脑的大容量比起来,笔记本电脑硬盘的容量仍然落后许多。笔记本电脑的硬盘除了对磁盘有体积较小和数量较少的要求之外,对功耗、耐用程度、抗震性及成本等的考虑,也让笔记

OpenGL ES学习总结:基础知识简介

什么是OpenGL ES? OpenGL ES (为OpenGL for Embedded System的缩写) 为适用于嵌入式系统的一个免费二维和三维图形库。 为桌面版本OpenGL 的一个子集。 OpenGL ES管道(Pipeline) OpenGL ES 1.x 的工序是固定的,称为Fix-Function Pipeline,可以想象一个带有很多控制开关的机器,尽管加工

计算机基础知识复习9.6

点对点链路:两个相邻节点通过一个链路相连,没有第三者 应用:PPP协议,常用于广域网 广播式链路:所有主机共享通信介质 应用:早期的总线以太网,无线局域网,常用于局域网 典型拓扑结构:总线型 星型(逻辑总线型) 介质访问控制  静态划分信道 信道划分介质访问控制 频分多路复用FDM 时分多路复用TDM 波分多路复用WDM 码分多路复用CDM 动态分配信道 轮询访问介质访问控

Gitflow基础知识

0.理想状态 现状 听完后的理想状态 没使用过 git 知道 git 是什么,会用 git 基础流程命令 用过 git,但只通过图形化界面操作 脱离图形化界面操作,通过 git 命令操作 会 git 命令 掌握 gitflow 规范,合理使用 rebase 和解决代码冲突问题 1.Git 的基础流程&命令 1.1 基础概念 工作区:代码生产基地,pycharm

[JAVA基础知识汇总-1] 创建线程的几种方式

文章目录 1. 继承Thread类2. 实现Runnable接口3. 实现Callable接口4. 线程池 可以认为有四种方式,也可以认为有一种,因为都跟Runnable接口有关 1. 继承Thread类 代码 public class Thread1ExtendsThread extends Thread {// public Thread1(String n