观察计算属性

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)

  • 我只有在计算属性包含对象时才遇到问题。然后我不得不做一个深度观察:`watch:{ myComputedProperty : { handler(newVal){ //do something when change发生}, deep: true}}` (5认同)
  • 好吧,我会再次尝试这个,但有时候我无法得到计算属性的事件,所以我不得不最终使用数据属性,而这通常是计算属性的副本.是否有任何理由导致计算属性失败触发监视事件? (4认同)
  • @Kendall 我遇到了同样的问题,计算的更改不会触发监视处理程序,您对此有任何进展吗? (3认同)
  • @Kendall我不确定为什么会发生这种情况,如果你可以将相关代码放在不起作用的地方,那么有人可能会指出一些警告或错误。 (2认同)
  • @Kendall似乎一旦计算函数中抛出错误,它就不会再触发观察者,请参阅小提琴http://jsfiddle.net/j7pLbtdz/ (2认同)

小智 6

computed: {
  name: {
    get: function(){
      return this.name;
    }
  }
},
watch: {
  name: function(){
    console.log('changed');
  }
}
Run Code Online (Sandbox Code Playgroud)

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


Ily*_*ich 5

以下是在 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)