面试题答案
一键面试derived计算属性的作用
在Svelte中,derived
计算属性用于根据一个或多个现有的Store(状态容器)的值,创建一个新的衍生值。它会自动追踪依赖的Store值的变化,并在依赖值变化时重新计算衍生值,从而提供一种简洁的方式来处理复杂的状态衍生逻辑。这有助于避免在组件中编写大量重复的逻辑来处理状态变化的响应。
示例代码
<script>
import { writable, derived } from'svelte/store';
// 创建两个可写的Store
const count1 = writable(1);
const count2 = writable(2);
// 使用derived创建一个衍生的Store
const sum = derived([count1, count2], ([$count1, $count2]) => {
return $count1 + $count2;
});
</script>
<p>count1: {$count1}</p>
<p>count2: {$count2}</p>
<p>sum: {$sum}</p>
<button on:click={() => count1.update(n => n + 1)}>Increment count1</button>
<button on:click={() => count2.update(n => n + 1)}>Increment count2</button>
在上述示例中:
- 首先创建了两个可写的Store
count1
和count2
,并初始化为1
和2
。 - 然后使用
derived
函数,传入一个包含count1
和count2
的数组作为依赖。derived
回调函数接收解包后的依赖值$count1
和$count2
,返回它们的和作为衍生值。这个衍生值存储在sum
这个新的Store中。 - 在模板部分,展示了
count1
、count2
和衍生的sum
的值。并且通过按钮点击事件来更新count1
和count2
,从而触发sum
的重新计算并更新显示。