简体   繁体   English

观看,将相同的代码应用于2种不同的功能

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

I don't know if the title is the best to describe my problem, but was the best way to introduce my daubt. 我不知道标题是否是描述我的问题的最好方法,但不是介绍我的涂抹方法的最好方法。

So basically i have this: 所以基本上我有这个:

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

as you can see, there are just 1 think that changes, that is the this.progressMonster and this.progressYou, i really want to optimize this into a function and really need to know how to that, how can i pass trough a function the name of the data variable that i wanna apply? 如您所见,只有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);
    }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM