Svelte 5 重寫之后即將帶來(lái)的巨大變化
不知不覺(jué),Svelte即將發(fā)布第5個(gè)版本了,而這個(gè)版本,即將帶來(lái)翻天覆地的變化。
首先,Svelte 5 引入了符文(runes)和片段(snippets)的概念。
?? 符文(runes)
?? $state
<script>
// 以前的寫法
// let count = 0
let count = $state(0);
</script>
<button on:click={() => count++}>
clicks: {count}
</button>
$state的引入,本質(zhì)上是對(duì)響應(yīng)式的加強(qiáng)。早期版本的響應(yīng)式只能存在于組件的頂層,函數(shù)內(nèi)部是無(wú)法返回響應(yīng)式的數(shù)據(jù)的,但是現(xiàn)在,我們可以像下面一樣通過(guò)函數(shù)返回響應(yīng)式的數(shù)據(jù)了。
export function createCounter() {
let count = $state(0);
function increment() {
count += 1;
}
return {
get count() {
return count;
},
increment
};
}
<script>
import { createCounter } from './counter.svelte.js';
const counter = createCounter();
</script>
<button on:click={counter.increment}>
clicks: {counter.count}
</button>
請(qǐng)注意,我們?cè)诜祷氐膶?duì)象中使用get屬性,因此它始終引用當(dāng)前值而不是調(diào)用函數(shù)counter.count時(shí)的值。
??$derived
如果說(shuō)和react的useState一樣,那么$derived就和useMemo一樣,它們都是聲明一個(gè)派生狀態(tài)。
<script>
let count = $state(0);
// 以前是這樣寫的
// $: double = count * 2
let double = $derived(count * 2);
</script>
<button on:click={() => count++}>
{double}
</button>
<p>{count} doubled is {doubled}</p>
和非符文模式相比,$: double = count * 2只能在dom更新后更新double值,但是在符文模式下,count變化,立馬更新double的值。
$effect
<script>
let count = $state(0);
let double = $derived(count * 2);
// 這是以前的寫法
// $: {
// console.log({ count, double });
// }
$effect(() => {
// mounted、updated的時(shí)候觸發(fā)
console.log({ count, double });
return () => {
// idestroyed時(shí)觸發(fā)
console.log('cleanup');
};
});
</script>
<button on:click={() => count++}>
{double}
</button>
<p>{count} doubled is {doubled}</p>
$effect最大的好處是可以返回一個(gè)組件銷毀時(shí)的回調(diào)函數(shù)了。
??$effect.pre
<script>
import { tick } from 'svelte';
let div;
let messages = [];
$effect.pre(() => {
if (!div) return; // not yet mounted
// reference `messages` so that this code re-runs whenever it changes
messages;
// autoscroll when new messages are added
if (
div.offsetHeight + div.scrollTop >
div.scrollHeight - 20
) {
tick().then(() => {
div.scrollTo(0, div.scrollHeight);
});
}
});
</script>
<div bind:this={div}>
{#each messages as message}
<p>{message}</p>
{/each}
</div>
這種方法取代了beforeUpdate方法。
??$props
要聲明組件道具,請(qǐng)使用$props符文:
let { optionalProp = 42, requiredProp } = $props();
let { a, b, c, ...everythingElse } = $props<MyProps>();
$props保留了children屬性,所以記得不要覆蓋該屬性。
??Snippets
片段的引入極大的提高了開(kāi)發(fā)效率,以前我們可能會(huì)這樣寫:
{#each images as image}
{#if image.href}
<a href={image.href}>
<figure>
<img
src={image.src}
alt={image.caption}
width={image.width}
height={image.height}
/>
<figcaption>{image.caption}</figcaption>
</figure>
</a>
{:else}
<figure>
<img
src={image.src}
alt={image.caption}
width={image.width}
height={image.height}
/>
<figcaption>{image.caption}</figcaption>
</figure>
{/if}
{/each}
但是現(xiàn)在,我們可以使用片段的功能復(fù)用代碼。
{#snippet figure(image)}
<figure>
<img
src={image.src}
alt={image.caption}
width={image.width}
height={image.height}
/>
<figcaption>{image.caption}</figcaption>
</figure>
{/snippet}
{#each images as image}
{#if image.href}
<a href={image.href}>
{@render figure(image)}
</a>
{:else}
{@render figure(image)}
{/if}
{/each}
當(dāng)然,你可以這樣帶入?yún)?shù)。
{#snippet figure({ src, caption, width, height })}
<figure>
<img alt={caption} {src} {width} {height} />
<figcaption>{caption}</figcaption>
</figure>
{/snippet}
另外,你還可以將片段傳遞給組件。
<script>
import Table from './Table.svelte';
const fruits = [
{ name: 'apples', qty: 5, price: 2 },
{ name: 'bananas', qty: 10, price: 1 },
{ name: 'cherries', qty: 20, price: 0.5 }
];
</script>
{#snippet header()}
<th>fruit</th>
<th>qty</th>
<th>price</th>
<th>total</th>
{/snippet}
{#snippet row(d)}
<td>{d.name}</td>
<td>{d.qty}</td>
<td>{d.price}</td>
<td>{d.qty * d.price}</td>
{/snippet}
<Table data={fruits} {header} {row} />
片段的功能呢和插槽的功能十分相似,但是它又比插槽方便,所以新版本即將棄用插槽的功能。
?? 事件處理程序
?? 放棄on:,采用onclick
<script>
let count = $state(0);
</script>
<!-- <button on:click={() => count++} -->
<button onclick={() => count++}>
clicks: {count}
</button>
??事件修飾符的邏輯被修改
<script>
function once(fn) {
return function (event) {
if (fn) fn.call(this, event);
fn = null;
};
}
function preventDefault(fn) {
return function (event) {
event.preventDefault();
fn.call(this, event);
};
}
</script>
<!--<button on:click|once|preventDefault={handler}>...</button>-->
<button onclick={once(preventDefault(handler))}>...</button>
這樣的好處是onclick能與現(xiàn)代事件處理程序一起使用了。
三個(gè)修飾符 - capture、passive和nonpassive- 不能表示為包裝函數(shù),因?yàn)樗鼈冃枰谑录幚沓绦蚪壎〞r(shí)應(yīng)用,而不是在事件處理程序運(yùn)行時(shí)應(yīng)用。
<button onclickcapture={...}>...</button>?
?? 組件不在是類了
import { mount } from 'svelte';
import App from './App.svelte'
// 以前的寫法
// const app = new App({ target: document.getElementById("app") });
const app = mount(App, { target: document.getElementById("app") });
export default app;
??總結(jié)
總的來(lái)說(shuō)Svelte5的重寫,降低了學(xué)習(xí)曲線,同時(shí)優(yōu)化了內(nèi)部邏輯,可以更靈活的控制響應(yīng)式的精度和層級(jí)。