簡體   English   中英

觀看,將相同的代碼應用於2種不同的功能

[英]Watch, apply same code to 2 different functions

我不知道標題是否是描述我的問題的最好方法,但不是介紹我的塗抹方法的最好方法。

所以基本上我有這個:

 watch: {
        valueYou: function(val){
            if(val < 15){
                this.progressYou.backgroundColor = "red";
            }
            else if(val < 50){
                this.progressYou.backgroundColor = "orange";
            }
            else{
                this.progressYou.backgroundColor = "green";
            }
        },
        valueMonster: function(val){
             if(val < 15){
                this.progressMonster.backgroundColor = "red";
            }
            else if(val < 50){
                this.progressMonster.backgroundColor = "orange";
            }
            else{
                this.progressMonster.backgroundColor = "green";
            }
        }
    }

如您所見,只有1個認為發生了變化,即this.progressMonster和this.progressYou,我真的很想將其優化為一個函數,並且確實需要知道如何做到這一點,我如何才能通過該函數我要應用的數據變量的名稱?

methods:{
    setBackground: function(val, element){
        if(val < 15){
            element.backgroundColor = "red";
        }
        else if(val < 50){
            element.backgroundColor = "orange";
        }
        else{
            element.backgroundColor = "green";
        }
    }
},
watch: {
    valueYou: function(val){
        this.setBackground(val, this.progressYou);
    },
    valueMonster: function(val){
        this.setBackground(val, this.progressMonster);
    }
}

創建一個將值轉換為顏色的函數:

function progressColor(p) {
  if (p < 15) return "red";
  if (p < 50) return "orange";
  return "green";
}

現在在您的對象中調用它:

watch: {
  valueYou: function (val) {
    this.progressYou.backgroundColor = progressColor(val);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM