[Vuejs]-Watch, apply same code to 2 different functions

0👍

Create a function that turns the value into the color:

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

Now call that in your object:

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

0👍

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);
    }
}

Leave a comment