鍍金池/ 問答/HTML5  網(wǎng)絡(luò)安全  HTML/ vue watch怎樣同時監(jiān)聽兩個值的變化并執(zhí)行方法?

vue watch怎樣同時監(jiān)聽兩個值的變化并執(zhí)行方法?

watch:{
      city(cur,old){
          this.loadTop();
      },
      country(cur,old){
//        this.loadTop();
      },
    }

如上,我想在城市和國家都變化的時候執(zhí)行刷新的方法,而不是單一執(zhí)行刷新

回答
編輯回答
詆毀你

?用computed:

loadTopResult () {
    if (this.city && this.country) {
       let res = this.loadTop()
       return res
    }
}

watch和computed的區(qū)別

2017年3月24日 10:48
編輯回答
淺時光

不能同時監(jiān)聽兩個值,
不過你可以

data () {
    return {
        city: '',
        oldCity: '',
        country: '',
        oldCountry: ''
    }
}
watch:{
      city(cur,old){
            if (this.country !== this.oldCountry) {
                this.loadTop();
                this.oldCountry = this.country
            }
      },
      country(cur,old){
            if (this.city !== this.oldCity) {
                this.loadTop();
                this.oldCity = this.city
            }
      },
    }
2018年7月2日 15:18
編輯回答
悶騷型

可以做個計數(shù)器
國家改變: count++;
城市改變: count++;

watch: {
    count(value){
       if(2 === value) {
            // 觸發(fā)code
            
           this.count = 0;
       }
   }
}

拋磚引玉啊, 方法比較拙, 對每個改變的執(zhí)行此處的判斷并沒有寫, 如果覺得方法可行再補上

不過如果是聯(lián)動的話, 國家變了, 城市自然為空, 所以你說的邏輯好像不成立, 我只是猜測.

2017年7月2日 09:02
編輯回答
心上人

用computed定義一個address對象吧,然后再去watch addres

data() {
  return {
    city: '',
    country: ''
  }
},
computed: {
  address() {
    const { city, country } = this
    return {
      city,
      country
    }
  }
},
watch: {
  address: {
    handler: function(val) {
      console.log('address change: ', val)
    },
    deep: true
  }
}

只的在computed里面調(diào)用也行,不過要使用$nextTick,不然值會是更新前的值。

data() {
  return {
    city: '',
    country: ''
  }
},
computed: {
  address() {
    const { city, country } = this
    this.$nextTick(() => {
      console.log(this.city, this.country, 3333)
    })
    return {
      city,
      country
    }
  }
},
2017年6月25日 11:05