VueJS:看两个属性

时间:2017-05-19 14:56:03

标签: javascript vue.js watch

假设我有两个数据属性:

data() {
  return {
    a: false, 
    b: false, 
  }
}

ab同时成为true时,我想执行相关任务。

如何在Vue中使用watch方法来实现此目的?

2 个答案:

答案 0 :(得分:9)

观察计算值。

computed:{
    combined(){
        return this.a && this.b
    }
}
watch:{
    combined(value){
        if (value)
            //do something
    }
}

上面使用$watch有一种简写。

vm.$watch(
  function () {
    return this.a + this.b
  },
  function (newVal, oldVal) {
    // do something
  }
)

答案 1 :(得分:0)

这与@Bert 建议的解决方案几乎相同。但您可以执行以下操作:

data() {
  return {
      combined: {
          a: false, 
          b: false, 
      }
  }
},

那么:

watch: {
    combined:{
        deep:true,
        handler
    }
}