【问题标题】:How to trigger a function when there is a value change in subscribed store in Svelte?当 Svelte 中的订阅存储发生值更改时如何触发函数?
【发布时间】:2021-02-27 16:53:38
【问题描述】:

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

stores.js

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

Component.svelte

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

【问题讨论】:

    标签: svelte svelte-3 svelte-component svelte-store


    【解决方案1】:

    在 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
    

    【讨论】:

      【解决方案2】:

      找到更清洁的解决方案

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

      【讨论】:

      • 不知道为什么这值得一票否决。我认为它很干净,符合 Svelte 的精神......
      • 其实当store的值为falsy的时候,这个是行不通的。您需要一个逗号而不是逻辑 AND:$: $comparedProducts, run(); 这将确保始终执行 run 函数,无论 store 的值如何。
      • 哇,这太棒了。我喜欢那是多么干净。干得好,苗条!
      【解决方案3】:

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

      store.js

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

      Component.svelte

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

      【讨论】:

        猜你喜欢
        • 2023-01-23
        • 1970-01-01
        • 2021-10-05
        • 1970-01-01
        • 2020-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多