18

When doing my frontend Vue project, I have the need of executing certain steps when element(s) are pushed into the list in data. However, when I pushed some initial values into the list in mounted(), the console.log() in the corresponding watch() outputs the same value for the newVal and oldVal parameter values.

Javascript/Vue code:

let app = new Vue({
    el: "#app",
    data: {
        testList: [],
    },
    mounted: function() {
        this.testList.push('a');
        this.testList.push('b');
        this.testList.push('c');
    },
    watch: {
        testList: {
            handler: function(newVal, oldVal) {
                console.log("new", newVal);
                console.log("old", oldVal);
            },
        },
    }
});

The console logging information: Console logging information

  1. Why do the newVal and oldVal hold the same value?
  2. Why isn't the watch() function being executed three times (since I pushed three times in mounted())?
3
  • Any luck if you add immediate: true to the watch function? So it will look like testList: { handler (...), immediate: true } Commented Jul 4, 2020 at 13:04
  • I tried using immediate: true but nothing happened. Finally I defined the function in handler in methods, mapped the handler of testList to the function in methods, and exectue manually the new method I defined and it worked. But this is not elegant 😂
    – Power_tile
    Commented Jul 5, 2020 at 14:45
  • I have the OP's same problem too; I decided to eliminate the watcher completely, even if one of the below proposed solutions works. Instead of risking performance overhead for the convenience of a top-level watcher, I'm using a simple chain of emits (when one particular property value changes) across many levels of hierarchy. This is much tighter and clear. I do use defineModel everywhere too, but I will resign to having a few extra lines for peace of mind. Use case: a very complex multi-facet search-and-filtering system that integrates with elasticsearch.
    – Kalnode
    Commented Apr 28 at 14:33

4 Answers 4

15

In addition, if someone is having this problem when watching nested properties changes, and using flag deep: true, it's expected that newValue and oldValue are the same (reference).

To overcome the issue, you could add computed property wrapping the data object that should be watched, and watch for changes on the computed property instead.

export default {
name: 'ExampleComponent',
data () {
    return {
        exampleObject: {
            name: 'User',
            email: 'Email'
        }
    }
},

computed: {
    computedObjectToBeWatched () {
        return Object.assign({}, this.exampleObject)
    }
},

watch: {
    computedObjectToBeWatched: {
        deep: true,
        handler (value, oldValue) {
            if (value.name !== oldValue.name) {
                console.log('changes occured')
            }
        }
    }
}

For Vue3/Composition API:

const usedToBeWatched = ref([]);
const watchedComputed = computed(() => structuredClone(toRaw(usedToBeWatched.value)));

watch(
  watchedComputed,
  (newVal, oldVal) => {
    console.log('watchedComputed', newVal, oldVal);
  },
);
3
  • 3
    And to get aquainted with this solution in the Vue 3 / Composition API syntax. const usedToBeWatched = ref([]); const watchedComputed = computed(() => structuredClone(toRaw(usedToBeWatched.value))); watch(watchedComputed, (newVal, oldVal) => { console.log('watchedComputed', newVal, oldVal) }));
    – Knogobert
    Commented Aug 14, 2023 at 13:46
  • 1
    I don't understand why the Vue framework can't just make a copy of the object before it updates it. They should add an option if you want this, like the "deep" option.
    – Donny V.
    Commented Apr 18 at 16:15
  • @equi this is not working when ref({ index1: 'some_value' }) Commented Aug 30 at 11:17
9

I have changed two thing

  1. do clone in watch
  2. added computed

It works fine now.

console.clear();

let app = new Vue({
    el: "#app",
    data: {
        testList: ['old'],
    },
    mounted: function() {
        this.testList.push('a');
        this.testList.push('b');
        this.testList.push('c');
    },
    watch: {
        testListClone: { //<-- Edited
            handler: function(newVal, oldVal) {
                console.log("new", newVal);
                console.log("old", oldVal);
            },
        },
    },
  computed:{  //<-- Added
    clonedItems: function(){
       return JSON.parse(JSON.stringify(this.testList))
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>

<div id="app"></div>

4
  • 2
    Cool! This works. However I believe there is a typo in this answer: in computed the variable is called clonedItems, but in watch it is called testListClone. Only when these two names are the same, the code could work. Can you change the typo and fix the indentation problem in computed so that I can mark this as the answer? Thx
    – Power_tile
    Commented Jul 5, 2020 at 14:51
  • Also, in this case, I found that watch is only executed one time. Why isn't it executed 3 times?
    – Power_tile
    Commented Jul 6, 2020 at 0:06
  • Can you explain why your stuff works? It should not be needed to do what you did Commented Aug 30 at 10:42
  • 1
    @Power_tile that is because Vue works that way, instead of executing it 3 times, it sees it changed, and only executes it once before nextTick, it is designed to do so Commented Aug 30 at 10:43
2

Because there is no answer as to why it returns the same value, I will say that your Array (or Object) is a reference, so both oldValue and newValue refer to the same reference.

No different than in pure JavaScript:

const oldArr = [{ name: 'jim' }];
const newArr = oldArr;
newArr[0].name = 'susan';
console.log({ oldArr, newArr });
// { oldArr: [ { name: 'susan' } ], newArr: [ { name: 'susan' } ] }

In order to make oldValue and newValue work as expected, you need to watch a primitive such as a String or Number.

You could do something hacky such as:

import { ref, watch } from 'vue';
// cloneDeep is used to deep-copy to avoid copying references
import { cloneDeep } from 'lodash.clonedeep';

const newArr = ref([]);
const oldArr = ref([]);

watch(() => newArr.value, () => {
    console.log('old value', oldArr.value);
    console.log('new value', newArr.value);

    // last step
    oldArr.value = cloneDeep(newArr.value);
}, { deep: true });
0

You can watch a copy of your object value, generated by arrow function in the 'watch' expression directly:

import { ref, watch } from 'vue';
const myArr = ref([]);

watch(() => ({...myArr.value}),  (newVal,oldVal) => {
   console.log('old value', oldVal);
    console.log('new value', newVal);
}, { deep: true });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.