What do you get if you do this?
window.productTaxesCalculator = (e) => {
console.log(e)
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi everyone,
I've got some trouble using alpine JS and Laravel Mix, and someone here will probably help me to understand and fix this
I'm using AlpineJS in my view like this:
<div x-data="productTaxesCalcultator()" x-init="init(X, Y)">
........
</div>
When I create the script tag in the same page, it's perfectly working
function productTaxesCalcultator() {
return {
ht: 0,
tva: 0,
ttc: '',
calculate: function() {
this.ttc = (this.ht + (this.ht * (this.tva / 100))).toFixed(2);
},
init(ht, tva) {
this.ht = parseFloat(ht);
this.tva = parseFloat(tva);
this.calculate();
}
}
}
But when I try to add this function inside my app.js (using laravel mix), I've got some weird errors.. Example: app.js:19980 Uncaught TypeError: Cannot set property 'ht' of undefined
The problem seems to be the "this" scope I guess
Here is what's look like my app.js
require('./bootstrap');
import 'alpinejs';
window.productTaxesCalculator = () => {
return {
ht: 0,
tva: 0,
ttc: '',
calculate: () => {
this.ttc = (this.ht + (this.ht * (this.tva / 100))).toFixed(2);
},
init: (ht, tva) => {
this.ht = parseFloat(ht);
this.tva = parseFloat(tva);
this.calculate();
}
}
}
What did I miss ? How can I fix that problem ?
Thanks
Ok thank you everyone for helping but I've found out...
The fat arrows function where the problem, I used normal function and the scope was working.
Please or to participate in this conversation.