N
N
Nik17122018-02-19 19:24:30
JavaScript
Nik1712, 2018-02-19 19:24:30

How to get key from json object received via ajax inside component with v-for?

There is a component inside html with conditional rendering

<cart-item v-for="(product, key, index) in products" :product="product" :key="index">
</cart-item>

Vue.component('cart-item', {
            props: ['product'],
            template:'<div>{{ product }} {{ key }}</div>'
        });
var app = new Vue({
    el: '#app',
    data: function () {
        return {
            products: [];
        };
    },
    beforeCreate: function () {
        var self = this;
        axios.get('http://localhost:3000/cart')
            .then(function (response) {
                self.products = response.data.products;
            })
            .catch(function (error) {
                console.log(error);
            });
    }
});

through ajax request we get json like
{
  "products":{
    "0968757":{
    "imageUrl":"//54754.jpg",
    "name":"rthrthtr",
    },
    "34364326":{
    "imageUrl":"//657457.jpg",
    "name":"rthrthtr",
    }
  }
}

How to get keys from products inside a component? In theory, they seem to need to be declared in props, but an error occurs

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-02-19
@Nik1712

How to get keys from products inside a component? In theory, they seem to need to be declared in props

Why didn't they announce it?
Very informative. For clairvoyants.
Are you sure there should be a semicolon here? Perhaps instead of biting your teeth at using frameworks, you should learn the basics of the language?
So, now what to do:
1. Specify the key from products to props, and use it in the template:
Vue.component('cart-item', {
  props: ['product', 'productKey'],
  template:'<div>{{ product }} {{ productKey }}</div>'
});

2. Your v-for will also look a little different:
<cart-item
  v-for="(product, key) in products"
  :product="product"
  :product-key="key"
  :key="key"
></cart-item>

UPD. It might be worth making products an array upon getting the data, and the keys properties of the array elements. Then you don't have to pass an additional parameter to the component.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question