Replies: 1 comment
-
I would only recommend the use of classes if you really need the performance boost they provide. Plain objects that are used with For classes you can use the second argument to <script>
class Counter {
value = $state(0)
}
const counter = new Counter();
</script>
<button onclick={() => counter.value++}>
clicks: {counter.value}
</button>
<pre>{JSON.stringify(counter, ['value'], 2)}</pre> Alternatively you could also add a <script>
class Counter {
value = $state(0)
toJSON() {
return {
value: this.value,
}
}
}
const counter = new Counter();
</script>
<button onclick={() => counter.value++}>
clicks: {counter.value}
</button>
<pre>{JSON.stringify(counter, null, 2)}</pre> |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
How to use JSON.stringify with class instances that use $state runes for properties?
When I try to convert a class instance to JSON that contains properties with $state, those properties are ignored in the resulting JSON.
Beta Was this translation helpful? Give feedback.
All reactions