The problem with your code is that in razor pages the @ sign is used to toggle between C# and HTML code. There are actually two solutions.
- You can simply escape the
@ sign by typing @@
Taken from the alpine example page this would look like this
<button x-data @@click="$store.darkMode.toggle()">Toggle Dark Mode</button>
...
<div x-data :class="$store.darkMode.on && 'bg-black'">
...
</div>
<script>
document.addEventListener('alpine:init', () => {
Alpine.store('darkMode', {
on: false,
toggle() {
this.on = !this.on
}
})
})
</script>
The other solution would be to use the x-on Event coming with Alpine JS. you can change the click line to this:
<button x-data x-on:click="$store.darkMode.toggle()">Toggle Dark Mode</button>
This will have the same effect without the need to escape any characters. x-on can also work with Change, KeyUp etc. Just pick whatever solution you like best!