Javascript 如何使用参数在svelte store中创建自定义方法?

Javascript 如何使用参数在svelte store中创建自定义方法?,javascript,svelte,svelte-store,Javascript,Svelte,Svelte Store,我想定制苗条店,可以这样称呼: $myStore.changeValue("my new value") // this would set new value to writable store $mystore // this would return current value of the store 是否可以在苗条中使用?如果可以,我建议您使用内置的 const currentValue = $myStore; myStore.set('my new value'

我想定制苗条店,可以这样称呼:

$myStore.changeValue("my new value") // this would set new value to writable store
$mystore // this would return current value of the store

是否可以在苗条中使用?

如果可以,我建议您使用内置的

const currentValue = $myStore;
myStore.set('my new value');
请注意,您仅在访问值时使用
$myStore
语法,而不是在对其调用方法时使用。在幕后,这个

如果要在存储上定义新方法,可以将其添加到导出的存储中。商店只需定义一个
subscribe
方法即可满足要求

从'svelte/store'导入{writeable};
const store=writable('这是一个测试');
导出默认值{
订阅:store.subscribe,
changeValue:store.set
}
然后可以在组件中调用它


从“/myStore.js”导入myStore;
函数handleClick(){
myStore.changeValue(“新值”);
}
myStore:{$myStore}!
更新存储
试试这个方法

// 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>

//App.svelte
从“./store.js”导入{MyStore}
const myStore=myStore(“空”)
(myStore.changeValue((new Date()).toString())}>
存储:{$myStore}