flurpleplurple
flurpleplurple

Reputation: 1325

Display data in Vue.js with v-for

I'm making a simple shopping cart system using Laravel and Vue.js. I can successfully add items to my shopping basket and retrieve them to a certain point, but I'm having trouble actually outputting the items to the view.

When I hit my basket route, I load the basket view which triggers the following Vue code:

new Vue({
  el: '#basket',
  ready: function () {
    this.fetchBasket();
  },
  methods: {
    fetchBasket: function(){
      this.$http.get('api/buy/fetchBasket', function (basketItems) {
        this.$set('basketItems', basketItems);
      });
    }
  }
});

This works and I get data returned in the console:

{027c91341fd5cf4d2579b49c4b6a90da: 
{id: 1, name: "A Gnarly Tree", price: 15, quantity: 2}}
  027c91341fd5cf4d2579b49c4b6a90da:
  {id: 1, name: "A Gnarly Tree", price: 15, quantity: 2}
    id:1
    name:"A Gnarly Tree"
    price:15
    quantity:2

However, nothing appears in the view itself. I'm trying to use v-for to populate a table:

<tbody>
    <tr v-for="item in basketItems">
        <td>@{{ item.name }}</td>
        <td>@{{ item.price }}</td>
        <td>@{{ item.quantity }}</td>
        <td>@<button class="btn btn-primary">Update</button></td>
    </tr>
</tbody>

What am I doing wrong?

Upvotes: 1

Views: 936

Answers (1)

gurghet
gurghet

Reputation: 7707

You didn't initialize the basketItems in the data of your vue instance. Try to add:

...
el: '#basket',
data: { basketItems: [] }, // <-- this line
ready: function(){
  this.fetchBasket();
},
...

Also edit

this.$set('basketItems', basketItems);

to

Vue.set(this, 'basketItems', basketItems)

Upvotes: 1

Related Questions