Robbie Robbie - 22 days ago 9
Javascript Question

Vue.js Uncaught TypeError: this.list.$remove is not a function

I keep getting the same error that this.list.$remove is not a function. I believe it has something to do with the html markup but not sure. Can anyone point me in the right direction? I have been struggling for the last 2 days.

Vue.component('cart-co', {

template: '#cart-template',

data: function() {
return {
list: []
}
},

ready: function() {
$.getJSON('cart/content', function(data) {
this.list = data;
}.bind(this));
},

methods: {
removeItem: function(item) {
console.log(item);
this.list.$remove(item);
}
}
});


new Vue({
el: 'body',
});


Here is my cart section:

<cart-co></cart-co>

<template id="cart-template">
<div class="cart-content-wrapper">
<div class="cart-content" >
<ul v-if="list" class="scroller" style="height: 250px;">

<li v-for="item in list">
<a href="item.html"><img src="assets/temp/cart-img.jpg" alt="" width="37" height="34"></a>
<span class="cart-content-count">@{{ item.quantity }}</span>
<strong><a href="item.html">@{{ item.name }}</a></strong>
<em>@{{ item.price | currency }}</em>
<a href="#" class="del-goods" v-on:click="removeItem(item)"><i class="fa fa-times"></i></a>
</li>

</ul>
<ul v-else class="scroller" style="height: 250px;">
<li>Shopping cart is empty</li>
</ul>
<div class="text-right">
<a href="{{ route('cart.show-cart') }}" class="btn btn-default">View Cart</a>
<a href="checkout.html" class="btn btn-primary">Checkout</a>
</div>
</div>
</div>
</template>

Answer

If the data coming back from your $.getJSON() call is an object (with each item in the cart being a key value pair), you can modify your code as follows to handle removing items.

Assumming data looks something like this:

{
   "item1": { "name": "Name 1", "quantity": 1, "price": 10 },
   "item2": { "name": "Name 2", "quantity": 1, "price": 10 },
   "item3": { "name": "Name 3", "quantity": 1, "price": 10 }
};

Pass the key of the item you want to remove in your delete link:

<a href="#" class="del-goods" v-on:click="removeItem($key)"><i class="fa fa-times"></i></a>

Change your removeItem() method to something like this:

removeItem: function(key) {
  Vue.delete(this.list, key);
}

This uses the Vue.delete method to delete the property (and ensures the view reacts to the change).