learncodes123
learncodes123

Reputation: 401

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)

Upvotes: 8

Views: 8682

Answers (2)

mcmimik
mcmimik

Reputation: 1833

Starting from version 3.4, you can use the oldValue parameter in the computed callback as shown below:

const result = computed((oldValue) => `${oldValue}, ${some.value}`);

For more details, see the docs on types or the "Computed Stability" section.

Upvotes: 1

Daniel
Daniel

Reputation: 35684

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}`);
        }
    }
});

Upvotes: 11

Related Questions