Watching computed properties

Vue ComponentVuejs2Computed Properties

Vue Component Problem Overview


I have a component with the following hash

{ 
  computed: { 
    isUserID: { 
      get: function(){
         return this.userId? 
      } 
  }
}

Should I be watching isUserID or userId for changes? Can you watch computed properties?

Vue Component Solutions


Solution 1 - Vue Component

Yes, you can setup watcher on computed property, see the fiddle.

Following is the code to set watch on computed property:

const demo = new Vue({
    el: '#demo',

    data() {
        return {
            age: ''
        };
    },

    computed: {
        doubleAge() {
            return 2 * this.age;
        }
    },

    watch: {
        doubleAge(newValue) {
            alert(`yes, computed property changed: ${newValue}`);
        }
    }
});

Solution 2 - Vue Component

computed: {
  name: {
    get: function(){
      return this.name;
    }
  }
},
watch: {
  name: function(){
    console.log('changed');
  }
}

This way we can watch over the computed property if it is changed we get notified on the console.

Solution 3 - Vue Component

Here's how you do it in Vue 3 with Composition API:

<script setup>
  import { ref, computed, watch } from 'vue'

  const variable = ref(1)

  const computedProperty = computed(() => {
    return variable.value * 2
  })

  watch(computedProperty, (newValue, oldValue) => {
    console.log('computedProperty was ' + oldValue + '. Now it is ' + newValue + '.')
  })
</script>

<template>
  <button @click="variable++">Click me</button>
</template>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKArneaudView Question on Stackoverflow
Solution 1 - Vue ComponentSaurabhView Answer on Stackoverflow
Solution 2 - Vue ComponentDavid WilliamView Answer on Stackoverflow
Solution 3 - Vue ComponentIlyichView Answer on Stackoverflow