Re-use persist/localStorage vars #1831
-
Hey kind folks, I'm toying around with this and I can't get this to work. It's probably not a bug but me so I'm posting it in help first :-) <button
x-data="{ myVar: $persist(false) }"
x-text="myVar"
@click="myVar = true"
>
</button>
<div
x-data="{ myVar: $persist(false) }"
x-show="myVar"
>
Show when myVar = true
</div> So when you click the button you set myVar in localStorage to true. After a reload I would expect the second div to show since it has Thanks in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 8 replies
-
You are declaring The <div x-data="{ myVar: $persist(false) }">
<button
x-text="myVar"
@click="myVar = !myVar"
>
</button>
<div x-show="myVar">
Show when myVar = true
</div>
</div> |
Beta Was this translation helpful? Give feedback.
You are declaring
x-data
in two sibling elements. ChangingmyVar
on the first won't affect the second. Movingx-data
to a parent element fixes it.The
$persist()
plugin will automatically take care of stringifying and parsing its value to/from JSON. You can also remove bothx-effect
attributes.