JanakaDombawela's avatar

How to iterate thorough a Vue data inside mounted?

Hello,

I have following setup.

var data = {
    items: [],
    total: 0
};

var cart = new Vue({
    el: '#root',
    data: data,
    mounted: function () {
        var $this = this;
        axios.get(vue_items_url).then(function (response) {
            $this.items = response.data;
            var total = 0;
            for (var i = 0; i < $this.items.length; i++) {
                total += $this.items[i].price * $this.items[i].qty;
            }
            $this.total = total;
        }).catch(function (error) {
            console.log(error);
        });
    }
});

This does not iterate through items array. How to iterate through Vue object? Is there any proper way?

0 likes
3 replies
Yamen's avatar

Maybe

data.items.forEach(function(item){
    // your logic
});
3 likes
dev.kobus's avatar
const data = {
    items: [],
    total: 0
}

Object.keys(data).forEach(key => {
    let val = data[key] // value of the current key

})

Object.keys() returns all the keys of a object (obviously). then you can simply iterate through the keys and access the value with brackets

3 likes

Please or to participate in this conversation.