Ashraam
1 month ago
574
13
Mix

AlpineJS and Laravel Mix

Posted 1 month ago by Ashraam

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

Please sign in or create an account to participate in this conversation.