A
A
Artur Karapetyan2019-08-14 09:08:58
Vue.js
Artur Karapetyan, 2019-08-14 09:08:58

Is it possible to painlessly change an observable property in an observer?

Good day, I ran into a problem that I could not solve myself.
There is an array watcher:

this.$watch(
      'order.items',
      () => {
        this.getCalculation();
      },
      {
        deep: true
      }
    );

order.items is an array of objects
order.items

items: [
  {
    id: 123,
    price: 213,
    discount: 123,
    quantity: 1
  },
  { ... }
]


In the getCalculation() method, a request is sent via vuex to get the actual prices for items, after which the price and discount are overwritten in order.items.
getCalculation

// http.get('...')
          order.items.map(item => {
            const itemCalc = orderCalc.items.find(
              itemCalc => itemCalc.productId === item.productId
            );

            item.price = itemCalc.price;
            item.discount = itemCalc.priceDiscount;
          });
          commit('setOrder', order);


After that, the action in the observer repeats indefinitely, which is quite obvious, but how can this be avoided? And it's not entirely clear why the observer triggers the handler all the time, even if the same data is overwritten?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question