除了 writable
和 readable
儲存之外,Svelte 還提供用於在使用者介面中新增動態效果的儲存。
讓我們從將 progress
儲存變更為 tweened
儲存開始
App
<script>
import { tweened } from 'svelte/motion';
const progress = tweened(0);
</script>
按一下按鈕會導致進度條動畫到新值。不過,它有點像機器人而且不令人滿意。我們需要新增一個緩和函式
App
<script>
import { tweened } from 'svelte/motion';
import { cubicOut } from 'svelte/easing';
const progress = tweened(0, {
duration: 400,
easing: cubicOut
});
</script>
svelte/easing
模組包含 Penner 緩和方程式,或者您可以提供自己的p => t
函式,其中p
和t
都是介於 0 和 1 之間的值。
tweened
可用的完整選項集
delay
— 過渡開始前的毫秒數duration
— 過渡的毫秒持續時間,或(from, to) => milliseconds
函式,允許您(例如)為較大的值變更指定較長的過渡easing
—p => t
函式interpolate
— 自訂的(from, to) => t => value
函式,用於在任意值之間插值。預設情況下,Svelte 會在數字、日期以及形狀相同的陣列和物件之間插值(只要它們僅包含數字和日期或其他有效的陣列和物件)。如果您想要插值(例如)顏色字串或轉換矩陣,請提供自訂的插值器
您也可以將這些選項作為第二個引數傳遞給 progress.set
和 progress.update
,在這種情況下,它們會覆寫預設值。set
和 update
方法都會傳回一個 Promise,該 Promise 會在過渡完成時解析。
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
32
33
34
35
<script>
import { writable } from 'svelte/store';
const progress = writable(0.5);
</script>
<progress value={$progress}></progress>
<button onclick={() => progress.set(0)}>
0%
</button>
<button onclick={() => progress.set(0.25)}>
25%
</button>
<button onclick={() => progress.set(0.5)}>
50%
</button>
<button onclick={() => progress.set(0.75)}>
75%
</button>
<button onclick={() => progress.set(1)}>
100%
</button>
<style>
progress {
display: block;
width: 100%;
}
</style>