当Svelte中订阅的商店中的值发生变化时如何触发函数?

roh*_*ikr 12 svelte svelte-component svelte-store svelte-3

我的一个组件订阅了商店中的一个变量。每当该存储变量发生变化时,我想触发一个函数。

商店.js

    import { writable } from "svelte/store"; 
    export const comparedProducts = writable([1,2,3]);
Run Code Online (Sandbox Code Playgroud)

组件.svelte

    import { comparedProducts } from "../stores.js";
    
    //if there is a change in $comparedProducts trigger this function eg. ([1,2])
    const someFunction = () => {
      //do something
    }
Run Code Online (Sandbox Code Playgroud)

roh*_*ikr 24

找到了更清洁的解决方案

import { comparedProducts } from "../stores.js";
$: $comparedProducts, run();

function run(){
  //do something here
}
Run Code Online (Sandbox Code Playgroud)


OmG*_*G3r 7

在 componenet.svelte 中

    import { comparedProducts } from "../stores.js";
    
    //if there is a change in $comparedProducts trigger this function eg. ([1,2])
    const someFunction = () = >{
      // do something
    }
    
    // stores can be subscribed to using .subscribe()
    // each new value will trigger the callback supplied to .subscribe()
    
    let unsubscribeStore = comparedProducts.subscribe((currentValue) => {
        //currentValue == $comparedProducts
        someFunction()
    })

    // call unsubscribeStore() after finishing to stop listening for new values
Run Code Online (Sandbox Code Playgroud)