Ken*_*AUD 40 computed-properties vue-component vuejs2
我有一个包含以下哈希的组件
{
computed: {
isUserID: {
get: function(){
return this.userId?
}
}
}
Run Code Online (Sandbox Code Playgroud)
我应该观看isUserID还是userId改变?你能看到计算属性吗?
Sau*_*abh 76
以下是在计算属性上设置监视的代码:
const demo = new Vue({
el: '#demo',
data() {
return {
age: ''
};
},
computed: {
doubleAge() {
return 2 * this.age;
}
},
watch: {
doubleAge(newValue) {
alert(`yes, computed property changed: ${newValue}`);
}
}
});
Run Code Online (Sandbox Code Playgroud)
小智 6
computed: {
name: {
get: function(){
return this.name;
}
}
},
watch: {
name: function(){
console.log('changed');
}
}
Run Code Online (Sandbox Code Playgroud)
这样我们就可以监视计算属性,如果它发生更改,我们会在控制台上收到通知。
以下是在 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>
Run Code Online (Sandbox Code Playgroud)