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?
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.