查看计算属性

问题描述 投票:0回答:3

我有一个具有以下哈希的组件

{ 
  computed: { 
    isUserID: { 
      get: function(){
         return this.userId? 
      } 
  }
}

我应该关注

isUserID
还是
userId
来了解变化吗?你能看计算属性吗?

vue-component vuejs2 computed-properties
3个回答
145
投票

是的,您可以在 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}`);
        }
    }
});

7
投票
computed: {
  name: {
    get: function(){
      return this.name;
    }
  }
},
watch: {
  name: function(){
    console.log('changed');
  }
}

通过这种方式,我们可以监视计算属性,如果它发生更改,我们会在控制台上收到通知。


6
投票

以下是在 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>
© www.soinside.com 2019 - 2024. All rights reserved.