I'm using a store for a modal and like to use the magic $watch
method like so:
Alpine.store('modal', {
init() {
this.$watch('this.open', (val) => console.log(val))
// Here I like to do if(open) { document.body.classList.add('overflow-hidden') }
},
open: false,
id: null,
close() {
this.open = false
this.id = null
}
})
But I get TypeError: this.$watch is not a function
Wrap the second argument in an arrow function:
Alpine.store('modal', () => ({
init() {
this.$watch('this.open', (val) => console.log(val))
},
open: false,
id: null,
close() {
this.open = false
this.id = null
}
}))
Arrow functions capture the this
value of the enclosing context, thus giving you access to Alpine's magic methods.
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