2017-04-03 46 views
0

我正在使用VueJS來顯示雜貨列表。每個雜貨商品可以增加或減少。我寫了下面的函數遞減:當我將數組索引作爲變量存儲時,代碼不起作用

deleteItem: function(index) { 
    this.items[index].quantity -= 1; 
    if (this.items[index].quantity < 0) { 
    this.items[index].quantity = 0; 
    }; 
} 

我試圖讓我的代碼更乾燥,所以我試圖把this.items[index].quantity中的變量。我想知道爲什麼我的代碼不工作whenI做到這一點:

deleteItem: function(index) { 
    var itemQuantity = this.items[index].quantity 
    itemQuantity -= 1; 
    if (this.items[index].quantity < 0) { 
    this.items[index].quantity = 0; 
    }; 
} 
+0

,因爲它不是一個參考 – epascarello

回答

2

問題是你要修改,而不是一個參考一個

值類型,例如數字和布爾值,總是被複制。這意味着你會失去對價值來源的參考。

例子:

var obj = { 
 
    a: 1 
 
}; 
 

 
var a = obj.a; 
 
a += 1; 
 
console.log(a); // changed 
 
console.log(obj.a); // unchanged

你可以做的反而是抱到對象你有興趣,因爲對象總是一個參考基準。

var items = [ 
 
    { quantity: 0 }, 
 
]; 
 

 
var item = items[0]; 
 
console.log('Initial state:', item.quantity); 
 
item.quantity -= 1; 
 
console.log('After the change:', item.quantity); 
 
if (item.quantity < 0) { 
 
    item.quantity = 0; 
 
    console.log('After the correction:', item.quantity); 
 
}

1

可以,而不是直接通過項目指標:

new Vue({ 
 
    el: "#app", 
 
    data: function() { 
 
    \t return { 
 
    \t items: [ { name: 'Product 1', quantity: 15 }, 
 
     \t \t \t \t { name: 'Product 2', quantity: 2 }, 
 
     \t \t \t { name: 'Product 3', quantity: 12 } ] 
 
    } 
 
    }, 
 
    methods: { 
 
    addQuantity: function(item, quantityToAdd) { 
 
    \t if(item.quantity + quantityToAdd < 0){ 
 
     \t item.quantity = 0; 
 
     } else { 
 
     \t item.quantity += quantityToAdd; 
 
     } 
 
    }, 
 
    increment: function(item) { 
 
    \t this.addQuantity(item, 1); 
 
    }, 
 
    decrement: function(item) { 
 
    \t this.addQuantity(item, -1); 
 
    } 
 
    } 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script> 
 

 
<div id="app"> 
 

 
    <div v-for="item in items" :key="item"> 
 
    {{ item.name }} {{ item.quantity }} 
 
    
 
    <button @click="decrement(item)" type="button">Decrement</button> 
 
    <button @click="increment(item)" type="button">Increment</button> 
 
    </div> 
 

 
</div>