A
A
AspMaster2019-09-28 16:03:10
JavaScript
AspMaster, 2019-09-28 16:03:10

How to bypass this magic?

Wrote this code in vuex mutation:

ADD_TO_CART: function(state, payload) {
    let found = state.cartItems.find(i => i.id == payload.id);
    if (found){
        found.count = count + payload.count;
    }
     else {
        state.cartItems.push(payload);
    }
    window.localStorage.setItem('cart', JSON.stringify(state.cartItems));
  }

I get this magic: when there is already a product in the basket, but you need to add its quantity, then found.count = payload.count. That is, if before calling this function, found had count = 1, then call this function with payload.count = 5, then as soon as the found.count = 5 function begins, and after executing the line found.count += payload.count we will get found.count = 10. How does this even work?
Example (changed the code a little, but the result is the same):
//state.cartItems[index].count = 1, payload.count = 5 (под index подразумевается индекс объекта, который будем менять)
ADD_TO_CART: (state, payload) =>{
    //уже тут state.cartItems[index].count = 5, payload.count = 5 (а вот почему - хз)
    let index = state.cartItems.findIndex(i => i.id == payload.id);
    if (index > -1){
        state.cartItems[index].count += payload.count;
         //state.cartItems[index].count = 10, payload.count = 5
    }
     else {
        state.cartItems.push(payload);
    }
    window.localStorage.setItem('cart', JSON.stringify(state.cartItems));
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2019-09-28
@Azperin

I don't quite understand why you don't get the error count is not defined

apples = 5;
basket = 0;

basket = apples; // тупо присваем в корзину яблоки
basket += apples; // прибавляем яблок к тем, что уже есть корзине
basket = basket + apples; // тоже самое что и выше

Yes, I don't quite understand the logic. You find a product in, roughly speaking, a general state and change its account, naturally, the next time you have this account will be increased, because you changed it in the state.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question