[Vuejs]-Javascript calculate 2 states

3👍

Since your code snippets are really small i had to imagine the environment of that functions. But what i guessed works as expected – i don’t know why it’s not working for you.

Working example:

var shop = {
    products: [
        {
            price_pcs: 0,
            full_price: 19,
            qty: 5
        },
        {
            price_pcs: 0,
            full_price: 25,
            qty: 7
        }
    ],
    calculatePCSPrice: function(index) {
        this.products[index].price_pcs = (this.products[index].full_price / this.products[index].qty).toFixed(2);
    },

    calculateTotalPrice: function(index) {
        this.products[index].full_price = (this.products[index].price_pcs * this.products[index].qty).toFixed(2);
    },
    calculatePrice: function(index) {
        this.calculatePCSPrice(index);
        this.calculateTotalPrice(index);
    }
};

shop.calculatePrice(0);
shop.calculatePrice(1);
console.log(shop.products);

Leave a comment