2016-02-16 34 views
3

我一直得到同樣的錯誤,this.list。$ remove不是函數。我相信它與html標記有關,但不確定。任何人都可以將我指向正確的方向嗎?過去兩天我一直在掙扎。

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', 
}); 

這是我的車款:

<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> 
+0

我相信這個問題是代碼中的其他位置。我把你的代碼和調整它很微調,看看我是否有同樣的錯誤,但它工作正常:https://jsfiddle.net/crswll/g1a1q3k3/ –

+0

我擡頭看Vue Devtools,並注意到我得到的數據是對象一個對象而不是數組中的對象。所以我用虛擬數據替換爲一個數組的對象,它仍然給我同樣的錯誤。所以不是這樣。 我想知道如果Vue與其他JavaScript庫衝突? – Robbie

+0

嗯。畢竟,我認爲問題與物體有關。當列表是一個數組時,。$ remove會起作用。當列表是一個對象時。$ remove給出錯誤,這不是一個函數。我查閱了文檔,但沒有提及此方法的對象。對於http://vuejs.org/guide/list.html#Object_v-for有對Object v的引用。任何幫助指出我在正確的方向將不勝感激。 – Robbie

回答

3

如果您$.getJSON()電話回來的數據是一個對象(與車是一個鍵值對每一個項目),你可以修改你代碼如下處理刪除項目。

Assumming數據看起來是這樣的:

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

傳給你想在你的刪除鏈接刪除項目的關鍵:

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

removeItem()方法更改爲這樣的事情:

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

這使用Vue.delete方法來刪除屬性(並確保視圖對更改作出反應)。

+0

謝謝彼得,就是這樣。現在正從購物車中取出物品。 – Robbie

+1

對於在Vue2中遇到此問題的其他人,您必須瞭解數組更改檢測和突變方法:https://vuejs.org/v2/guide/list.html#Array-Change-Detection並調用removeItem(key )'它使用'this.list.splice(key,1);'。 –

1

$刪除不VUE JS 2.0可用...現在你可以使用

剪接(指數1) 「1意味着它從數組拼接一個元素」

相關問題