Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 543
李元秋 Avatar asked Jul 11 '19 07:07

李元秋


People also ask

How do you assign a console log to a variable?

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.

How do I print the value of a variable in console log?

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);

What is $$ in svelte?

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.

How do you declare a variable in svelte?

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.


3 Answers

I asked in Twitter, the answer is:

Screenshot of a twitter thread, see link below.

Link to the thread: https://twitter.com/liyuanqiu/status/1149235193296773122

like image 164
李元秋 Avatar answered Oct 21 '22 16:10

李元秋


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.

like image 27
2pha Avatar answered Oct 21 '22 18:10

2pha


You can do it like this:

let c = 0;
$: if (c >= 0) {
    console.log("yes");
}
like image 41
Mike Nikles Avatar answered Oct 21 '22 16:10

Mike Nikles