Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watching computed properties

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?

like image 449
KArneaud Avatar asked Dec 09 '16 19:12

KArneaud


3 Answers

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}`);
        }
    }
});
like image 158
Saurabh Avatar answered Dec 08 '22 00:12

Saurabh


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.

like image 22
David William Avatar answered Dec 07 '22 22:12

David William


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>
like image 34
Ilyich Avatar answered Dec 08 '22 00:12

Ilyich