V
V
Vadim Sutormin2021-03-03 09:09:58
Vue.js
Vadim Sutormin, 2021-03-03 09:09:58

Why can't I get the old value of an observable in Vue?

Listening through the watch object, I need to know the old value of one of the object's properties, but I only get the new properties. Why is that?

watch: {
worker: {
      handler: function(newWorker, oldWorker) {
      alert (newWorker.sum + ' ' + oldWorker.sum);
},
deep: true
}
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-03-03
@Wunder

We open the documentation , we read:

Note that when modifying (rather than replacing) an object or array, the old and new values ​​will be the same when the callback is called, since they refer to the same object or array. Vue does not save copies of the object before the change.

If you want to have access to the old value - do not keep track of the entire object, but only the desired property:
watch: {
  'obj.propName'(newValue, oldValue) {
    ...
  },
},

If you need to keep track of many properties at once, and you don’t want to create a separate observer for each ... Well, over there, in the quote from the documentation, it is transparently hinted what to do - instead of changing the property, replace the entire object with a new one. That is, it was obj.propName = value, but it will be . Well, then you can already compare the properties in the old and new objects to find which one was specifically changed. obj = { ...obj, propName: value }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question