Search code examples
vue.jsvuejs2

Access the previous value of computed VueJS


I am using computed to check when some information has changed.

When i click and computed is run, i can see both the new value in my data and the old value assigned to the computed function. This value is seen via the Chrome Vue Dev Tools.

What i want to do is access the data that computed saves, not returns. That is the data that was previously correct, but computed updated the return inside.

The reason i want to do this is to show the data doesn't match anymore and that something has changed.

selectedLenses: "30626146713652" <-- Data
changeSelectedLenses: "28717846790196" <-- Computed

click a button that runs the computed function and it changes to:

selectedLenses: "28717846790196" <-- Data
changeSelectedLenses: "30626146713652" <-- Computed (Want to access this data saved to the computed function)

Solution

  • If you're trying to watch for changes, using watch may be the way to go. It handles prev and next values, and you can assign it to watch your computed...

    new Vue({
        //...
    
        data() {
            return {
                selectedLenses: 0
            };
        },
    
        computed: {
            changeSelectedLenses() {
                return this.selectedLenses + 2;
            }
        },
    
        watch: {
            changeSelectedLenses(newValue, oldValue) {
                alert(`changeSelectedLenses computed property changed from ${oldValue} to ${newValue}`);
            }
        }
    });