Svelte教程:框架一些有趣的特性
没有特殊说明,下面的每个例子均是一个单独的
.svelte文件。
# 有趣的特性
# 另类的响应式写法
<script> let count = 1; // $: 表示这个变量在它的右值变化的时候会重新计算 // count 变化, doubled 和 quadrupled 这俩值也会跟着变 // 很类似 vue 的 computed $: doubled = count * 2; $: quadrupled = doubled * 2; // $: 也可以是一段逻辑 $: if (count >= 10) { alert(`count is dangerously high!`); count = 9; } </script>htmlcopy success
# 数组和对象的更新
<script> // 数组 let numbers = [1, 2, 3, 4]; $: sum = numbers.reduce((t, n) => t + n, 0); // 不起作用 function addNumber() { numbers.push(numbers.length + 1); } // 只有显式用等号赋值,才能触发响应式 // 需要多操作一下 function addNumber() { numbers.push(numbers.length + 1); // 显式赋值 numbers = numbers; } // 更简单地写法 function addNumber() { numbers = [...numbers, numbers.length + 1]; } // 再来一种 function addNumber() { numbers[numbers.length] = numbers.length + 1; } // 对象 let obj = { x: { k: 'k', }, }; $: ks = JSON.stringify(obj, null, 2); // 不生效 function addProp() { const x = obj.x; x.c = 'k'; } // 生效 function addProp() { obj.x.c = 'k'; } </script>htmlcopy success
# 将扩展运算符应用到 Props
<script> import Info from './Info.svelte'; const pkg = { name: 'svelte', version: 3, speed: 'blazing', website: 'https://svelte.dev' }; </script> <Info {...pkg}/> <!-- info.svelte --> <script> export let name; export let version; export let speed; export let website; </script>htmlcopy success
# 唯一标记每个列表项
<script> import Thing from './Thing.svelte'; let things = [ { id: 1, color: '#0d0887' }, { id: 2, color: '#6a00a8' } ]; </script> {#each things as thing (thing.id)} <Thing current={thing.color}/> {/each}htmlcopy success
# 将 Async/Await 与模板结合
<script> // example function let promise = async () => {}; </script> {#await promise} <p>...waiting</p> {:then number} <p>The number is {number}</p> {:catch error} <p style="color: red">{error.message}</p> {/await}htmlcopy success
# 事件修饰符
<button on:click|once|capture={handleClick}> Click me </button>htmlcopy success
所有修饰符:
- preventDefault
- 运行事件句柄之前先调用 event.preventDefault()
- stopPropagation
- 调用 event.stopPropagation()
- passive
- 改善触摸/滚轮事件的滚动性能
- capture
- 捕获阶段处理事件句柄
- once
- 句柄触发一次
- self
- 只有在 event.target 是元素本身时才触发句柄
# 组件间事件处理
- 父组件:
<Child on:xxx={handleXxx} /> - 子组件:
const dispatch = createEventDispatcher()dispatch('xxx', opts)
<!-- App.svelte --> <script> import Inner from './Inner.svelte'; function handleMessage(event) { alert(event.detail.text); } </script> <Inner on:message={handleMessage}/> <!-- Inner.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>htmlcopy success
# (DOM)事件转发
待完善
# 组合输入
待完善
# This
待完善
# 父子组件可直接绑定值
待完善
# 极简的生命周期
- onMount
- onDestroy
- beforeUpdate&afterUpdate
- tick
# Stores
待完善
# ContextApi
待完善
# 一些特殊标签
待完善
# Module ontext
待完善