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?
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}`);
}
}
});
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With