【问题标题】:How to make custom methods in svelte store with parameter?如何在带有参数的苗条商店中制作自定义方法?
【发布时间】:2021-04-02 20:14:12
【问题描述】:
我想制作可以这样调用的自定义苗条商店:
$myStore.changeValue("my new value") // this would set new value to writable store
$mystore // this would return current value of the store
在 Svelte 中可以吗?
【问题讨论】:
标签:
javascript
svelte
svelte-store
【解决方案1】:
如果可以的话,我会推荐使用内置的set method。
const currentValue = $myStore;
myStore.set('my new value');
请注意,您仅在访问值时使用$myStore 语法,而不是在对其调用方法时。在幕后,这个subscribes to the store。
如果要在商店中定义新方法,可以将其添加到导出的商店中。商店只需要定义一个subscribe 方法来兑现store contract。
import { writable } from 'svelte/store';
const store = writable('This is a test');
export default {
subscribe: store.subscribe,
changeValue: store.set
}
然后可以在您的组件中调用它。
<script>
import myStore from './myStore.js';
function handleClick() {
myStore.changeValue('new value');
}
</script>
<h1>myStore: {$myStore}!</h1>
<button on:click={handleClick}>
Update store
</button>
【解决方案2】:
试试这个方法
// store.js
import { writable } from 'svelte/store';
export function MyStore(value) {
const { subscribe, set, update } = writable(value)
return {
subscribe,
set,
update,
changeValue: function (value) {
// put your logic here
// call update method to make the store reactive when the value get changed
update((oldValue) => value)
},
}
}
使用自定义商店:
<script>
// App.svelte
import {MyStore} from './store.js'
const myStore = MyStore("Empty")
</script>
<button on:click={e=> (myStore.changeValue((new Date()).toString()))}>
Store: {$myStore}
</button>