'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?
Solution 1:[1]
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:[2]
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:[3]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Simon |
Solution 2 | Claus Wilke |
Solution 3 | Ilyich |