这是我第一次使用 Svelte,我正在尝试构建一个商店。 我阅读了文档here但有件事我不清楚。抱歉,如果这是一个愚蠢的问题。
基本上,我创建了一个可读存储(可读,因为它不会改变)和一个派生值。 现在我需要创建一个带有参数的派生函数。
stores.js
:
import { derived, readable, writable } from 'svelte/store'
export const dataset = readable([1, 3, 2, 5, 4, 2]);
export const sortedDataset = derived(dataset, ($dataset) => {
return $dataset.sort();
})
export function getCounterValue(value) { // <- how to implement something like this?
return dataset.filter((d) => d === value).length;
}
App.svelte
<script>
import {dataset, sortedDataset, getCounterValue} from './stores.js'
console.log('dataset:', $dataset);
console.log('sorted dataset:', $sortedDataset);
console.log('2 counter:', getCounterValue(2)); // <- how can I call the function?
</script>
可能吗?
最佳答案
您可以创建存储派生函数,只需从存储返回一个函数(存储本身不可调用):
export const getCounterValue = derived(dataset, $dataset => {
return value => $dataset.filter(d => d === value).length;
})
<script>
//...
console.log('2 counter:', $getCounterValue(2)); // $ required for store access
</script>
关于svelte - 创建带参数的派生函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72541151/