Monday 21 August 2023

In svelte, how to `console.log('yes')` when a variable changed?

let c = 0;
$: console.log(c);

If we want to print the value of c when it is changed, we can write like above.

Because c is used in $ directive literally, so this statement can be reactive to c.

But what if I just want to console.log('yes') when c is changed?

let c = 0;
$: console.log('yes');

Obviously, the statement console.log('yes') is not reactive to c.

Furthermore, if I still console.log(c) but put it into a function:

let c = 0;
function log() {
  console.log(c);
}
$: log();

log() is also not reactive to c.

So, what can I do if the reactive code doesn't literally contain the variable which I want to reactive to?



from In svelte, how to `console.log('yes')` when a variable changed?

No comments:

Post a Comment