我有一个具有以下哈希的组件
{
computed: {
isUserID: {
get: function(){
return this.userId?
}
}
}
我应该关注
isUserID
还是 userId
来了解变化吗?你能看计算属性吗?
是的,您可以在 compulated 属性上设置 watcher,请参阅 fiddle。
以下是设置计算属性监视的代码:
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');
}
}
通过这种方式,我们可以监视计算属性,如果它发生更改,我们会在控制台上收到通知。
以下是在 Vue 3 中使用 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>