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?
If you want to do this to an object that has been already logged (one time thing), chrome console offers a good solution. Hover over the printed object in the console, right click, then click on "Store as Global Variable". Chrome will assign it to a temporary var name for you which you can use in the console.
log() is a function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user. Syntax: console. log(A);
Reactive statements In a Svelte component, prefixing a statement with $: marks the statement as reactive — it will run whenever the variables referenced in that statement change. Here's a classic example. Whenever num changes, doubled is automatically set to the correct value.
Svelte uses the export keyword to mark a variable declaration as a property or prop, which means it becomes accessible to consumers of the component (see the section on attributes and props for more information). You can specify a default initial value for a prop.
I asked in Twitter, the answer is:
Link to the thread: https://twitter.com/liyuanqiu/status/1149235193296773122
I have recently been playing with svelte and needed to call a function when a property changed.
In Vue you would do it with watch
, but I could not find an equivilent in Svelte.
In my project have done it like this:
let c = 0;
$: if (c) {
console.log("yes");
}
I am not 100% sure if this is the correct way or not though.
Hopefully Rich Harris will chime in here as I would like to know.
You can do it like this:
let c = 0;
$: if (c >= 0) {
console.log("yes");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With