创建带参数的派生函数

mar*_*lle 2 svelte

这是我第一次使用 Svelte,我正在尝试构建一个商店。我在这里阅读了文档,但有些东西我不清楚。抱歉,如果这是一个愚蠢的问题。

基本上我创建了一个可读存储(可读,因为它不会改变)和一个派生值。现在我需要创建一个带有参数的派生函数。

这是我的代码

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;
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

是否可以?

H.B*_*.B. 6

您可以创建存储派生函数,只需从存储返回一个函数(存储本身不可调用):

export const getCounterValue = derived(dataset, $dataset => {
  return value => $dataset.filter(d => d === value).length;
})
Run Code Online (Sandbox Code Playgroud)
<script>
  //...
  console.log('2 counter:', $getCounterValue(2)); // $ required for store access
</script>
Run Code Online (Sandbox Code Playgroud)

REPL