• svelte初探-上


    数据模板
    • Svelte中数据模板类似vue中的“{{}}”,区别是svelte中使用“{}”
    • Svelte中不仅可以使用{}设置文本,也可以设置动态属性
    • 可以在{}中使用文本,原始的html,javascript表达式
    • 当为img标绑定属性时一定要加上alt,否则svelte会警告
    • 当属性值跟定义的变量名相同时可以使用简写方式‘xxx’
    • 使用html模板方式{@html xxx}
    <script>
    	let name = 'world';
    </script>
    <h1>Hello {name}!</h1>
    
    // 控制属性
    <script>
    	let src = 'tutorial/image.gif';
    </script>
    <img src={src} alt="test">
    <img {src} alt>
    
    // 使用html模板
    <script>
    	let string = `this string contains some HTML!!!`;
    </script>
    <p>{string}</p>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    css 样式
    • Svelte中书写样式很简单,使用标签即可
    • Svelte中的style默认隔离,不会影响子组件的样式,这一点与vue需要加上scoped不同
    组件
    • Svelte中定义一个组件仅需要声明一个以*.svelte*结尾的文件即可
    • 组件一般首字母大写用于区分一般标签
    • 组件引入与使用同vue
    //parent.svelte
    <script>
      	import Child from 'Child.svelte'
    </script>
    <p>我是父组件</p>
    <Child />
    
    //child.svelte
    <p>我是子组件</p>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    反应性能力
    • Svelte内部实现了DOM与程序状态保持同步的响应性系统,不同于vue及react的虚拟DOM,svelte将赋值语句替换成一些代码,这些代码将通知Svelte更新DOM
    • 使用$:监听数据变化,或者实现数据计算。类似vue中的watch及computed属性
    • 反应式语句可以使用{}组合一个代码块,甚至可以使用if判断语句
    • 数组更新不同于vue重新封装push,splice等方法实现更新操作,由于Svelte的反应性是由赋值语句触发的,所以需要依赖添加赋值语句或者使用es6扩展运算来更新操作
    • 对象的反应性赋值同数组
    • 经验法则:被更新的变量名称必须出现在赋值语句的左侧
    <script>
    	let count = 0;
    	$: doubled = count * 2; //类比computed
    	$: watch(count); //类比watch
    	$: {
    		console.log(`the count is ${count}`);
    		alert(`I SAID THE COUNT IS ${count}`);
    	}
    	$: if (count >= 10) {
    		alert(`count is dangerously high!`);
    		count = 9;
    	}
    	function watch(val){
    		console.log(val)
    	}
    	function handleClick() {
    		count += 1;
    	}
    </script>
    
    <button on:click={handleClick}>
    	Clicked {count} {count === 1 ? 'time' : 'times'}
    </button>
    
    <p>{count} doubled is {doubled}</p>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    属性(类比vue中的props)
    • Svelte中的属性只能在给定的子组件中访问
    • 在子组件中使用需要使用export语法来定义
    • 可以指定子组件的默认属性值
    • 组件含有一个对象属性,可以利用…语法将他们传递到一个组件上去,而不用一一指定
    //parent.svelte
    <script>
    	import Nested from './Nested.svelte';
    </script>
    <Nested answer={42}/>
    
    //child.svelte
    <script>
    	export let answer;
    </script>
    <p>The answer is {answer}</p>
    
    //默认属性值
    <script>
    	export let answer = 'defaultValue';
    </script>
    //父中引用
    <Nested/>
    
    //对象属性
    <Info {...pkg}/> //父组件
    <script> // 子组件
    	export let name;
    	export let version;
    	export let speed;
    	export let website;
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    逻辑
    • if-else、else及if-elseif-else(类比vue的条件渲染v-if v-else v-else-if)
    // 简单判断
    {#if user.loggedIn}
    	<button on:click={toggle}>
    		Log out
    	</button>
    {/if}
    // 分支判断
    {#if user.loggedIn}
    	<button on:click={toggle}>
    		Log out
    	</button>
    {:else}
    	<button on:click={toggle}>
    		Log in
    	</button>
    {/if}
    // 多分支判断
    {#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}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • {@each a as arr}循环语句(类比vue列表渲染v-for),建议添加key值,Svelte将按照key值来进行想要的操作
    <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>
    	{#each cats as { id, name }, i} 
    		<li><a target="_blank" href="https://www.youtube.com/watch?v={id}">
    			{i + 1}: {name}
    		</a></li>
    	{/each}
    </ul>
    // 绑定key
    {#each things as thing (thing.id)}
    	<Thing current={thing.color}/>
    {/each}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • await块(个人感觉实际使用频次不高,故简单介绍)
    <script>
    <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 number}
    	<p>The number is {number}</p>
    {:catch error}
    	<p style="color: red">{error.message}</p>
    {/await}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    事件
    • Svelte中的事件与react有点类似:以on开头接上事件名称 on:click on:mousemove等
    • 事件修饰符,可以将多个事件修饰符放在一起使用on:click|once|capture={…}
    修饰符作用
    preventDefault调用event.preventDefault() ,在运行处理程序之前调用。比如,对客户端表单处理有用
    stopPropagation调用event.stopPropagation(),阻止事件冒泡
    passive优化了对 touch/wheel 事件的滚动表现(Svelte 会在合适的地方自动添加滚动条)
    capture在 capture 阶段而不是bubbling 阶段触发事件处理程序
    once运行一次事件处理程序后将其删除
    self仅当 event.target 是其本身时才执行
    • 组件事件,子组件需要实例化createEventdispatcher(类比$emit)
    • 组件事件转发需要通过中间组件通信中转。Svelte 设立了一个简写属性 on:message。 message 没有赋予特定的值得情况下意味着转发所有massage事件
    • DOM事件转发,只需要在引用的组件内部添加相应的事件即可,这样就可以实现在子组件中点击使用父组件中的方法
    //parent.svelte
    <script>
    	import Inner from './Inner.svelte';
    	function handleMessage(event) {
    		alert(event.detail.text);
    	}
    </script>
    <Inner on:message={handleMessage}/>
    //child.svelte
    <script>
    	import { createEventDispatcher } from 'svelte';
    	const dispatch = createEventDispatcher();
    	function sayHello() {
    		dispatch('message', {
    			text: 'Hello!'
    		});
    	}
    </script>
    
    <button on:click={sayHello}>
    	Click to say hello
    </button>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
  • 相关阅读:
    C语言打印九九乘法表
    Linux 应用---make及makefile的编写
    SQLAlchemy使用教程(以SQLite为例)
    【opencv-python】基于createShapeContextDistanceExtractor的形状距离匹配
    TypeError: Cannot read properties of undefined (reading ***)
    LeetCode 209. 长度最小的子数组
    R语言七天入门教程三:学习基本结构
    【面试必刷101】链表
    邮件安全不容忽视,教你如何防止邮件泄密!
    【JAVASE】面向对象的三大特征
  • 原文地址:https://blog.csdn.net/V_AYA_V/article/details/126778639