我不知道标题是否最能描述我的问题,但这是介绍我的daubt的最佳方式。
基本上我有这个:
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,我真的想把它优化成一个函数,真的需要知道怎么做,我怎么能通过低谷一个函数我想申请的数据变量的名称?
答案 0 :(得分: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);
}
}
答案 1 :(得分:0)
创建一个将值转换为颜色的函数:
function progressColor(p) {
if (p < 15) return "red";
if (p < 50) return "orange";
return "green";
}
现在在你的对象中调用它:
watch: {
valueYou: function (val) {
this.progressYou.backgroundColor = progressColor(val);
}
}