· front end · 1 min read

Vue Tip: Getting the preveious value of computed property

In Vue's documentation I realised something I never see before. It's about getting the previous value of a computed property. Generally I was achieving this by using a `watch` function. But Vue has a better way to do this. Let's jump into it.

The way to get and use previous value

In Vue’s documentation I realised something I never see before. It’s about getting the previous value of a computed property. Generally I was achieving this by using a watch function. But Vue has a better way to do this. Let’s jump into it.

<script setup lang="ts">
import { computed, ref } from 'vue';
const count = ref(1);
const doubleCount = computed((oldVal) => {
    if (oldVal !== undefined) {
        console.log('Previous value:', oldVal);
    }
    return count.value * 2;
});
</script>
<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Double Count: {{ doubleCount }}</p>
    <button @click="count++">Increment</button>
  </div>
</template>

In the above code, we have a count ref and a doubleCount computed property. The computed property takes a function that receives the previous value as an argument. This way, we can easily access the previous value without needing to set up a separate watcher.

Back to Blog