개발하자

Svelte의 구독 스토어에서 값 변경이 있을 때 기능을 트리거하는 방법은 무엇입니까?

Cuire 2023. 1. 1. 12:41
반응형

Svelte의 구독 스토어에서 값 변경이 있을 때 기능을 트리거하는 방법은 무엇입니까?

내 구성 요소 중 하나가 스토어의 변수에 가입되어 있습니다. 해당 스토어 변수가 변경될 때마다 함수를 트리거하고 싶습니다.

stores.js

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

Component.svelt

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



componentnet.svelt에서

    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



보다 깨끗한 솔루션 발견

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

function run(){
  //do something here
}



카운터 데모 작업 및 세부 사항

store.js

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

Component.svelt

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

    
function foo($count) {
   console.log($count)
}



@rohanharikr의 답변에 추가.

$: $comparedProducts, (() => {
  // do something here
})();

당신은 자동으로 그 기능을 만들고 구독을 취소하는 익명의 기능을 만들 수 있다.


반응형