组件中的
我的一个组件订阅了存储中的一个变量。每当存储变量发生变化时,我都想触发一个函数。
stores.js
import { writable } from "svelte/store";
export const comparedProducts = writable([1,2,3]);
组件速度
import { comparedProducts } from "../stores.js";
//if there is a change in $comparedProducts trigger this function eg. ([1,2])
const someFunction = () => {
//do something
}
找到了更清洁的解决方案
import { comparedProducts } from "../stores.js";
$: $comparedProducts, run();
function run(){
//do something here
}
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
添加到@rohanharikr的答案
$: $comparedProducts, (() => {
// do something here
})();
您可以创建一个匿名函数,该函数将自动创建和取消订阅该函数。
更多细节和工作Repl演示计数器。
store.js
import { writable } from "svelte/store";
export const count = writable(0);
组件速度
import { count } from "../store.js";
$: if($count > 0) { foo($count) }
function foo($count) {
console.log($count)
}