4

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

商店.js

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

组件.svelte

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

3 回答 3

12

找到了更清洁的解决方案

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

function run(){
  //do something here
}
于 2020-11-18T05:54:27.223 回答
4

在 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
于 2020-11-16T13:32:58.980 回答
0

更多细节和工作Repl演示了一个计数器。

store.js

import { writable } from "svelte/store"; 
export const count = writable(0);

组件.svelte

import { count } from "../store.js";
$: if($count > 0) { foo($count) }

    
function foo($count) {
   console.log($count)
}
于 2021-09-22T20:42:58.393 回答