除了 writable 和 readable 存储外,Svelte 还提供了一些存储,用于为用户界面添加运动效果。
让我们从将 progress 存储更改为 tweened 存储开始。
应用
<script>
import { tweened } from 'svelte/motion';
const progress = tweened(0);
</script>点击按钮会导致进度条动画到新值。不过,它有点机械化,而且不令人满意。我们需要添加一个缓动函数。
应用
<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>