반응형
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
})();
당신은 자동으로 그 기능을 만들고 구독을 취소하는 익명의 기능을 만들 수 있다.
반응형
'개발하자' 카테고리의 다른 글
Flatter에서 행()의 배경색을 설정하는 방법은 무엇입니까? (0) | 2023.01.02 |
---|---|
코드(파이썬)에서 주피터 노트북을 생성/수정하는 방법은 무엇입니까? (1) | 2023.01.02 |
어떻게 하면 쿠버네티스가 이미지를 다시 끌어오도록 할 수 있을까요? (0) | 2022.12.31 |
pm2를 사용하여 tsconfig-paths로 typescript 빌드 실행 (0) | 2022.12.31 |
테라폼이 "이미 존재하는" 모든 리소스를 자동으로 가져오도록 하는 방법은 무엇입니까? (0) | 2022.12.30 |