vue methods方法互相调用,this.data数据赋值问
2018-12-07 本文已影响0人
醉笙情丶浮生梦
写一个px,vw互相转换小工具碰到的问题。记录一下
html 代码
<div id="app">
<div>图片宽度<input type="number" v-model.number="imgWidth">px
<span class="left">图片高度<input type="number" v-model.number="imgHeight"> px</span>
</div><br>
<div>宽度 <input type="number" v-model="pxWidth">px
<span class="left">宽度<input type="number" v-model.number="vwResult"> vw</span></div><br>
<div>高度 <input type="number" v-model="pxHeight">px
<span class="left">高度<input type="number" v-model.number="vhResult"> vh</span></div><br>
</div>
关键javascrip
methods: {
//生成vw和vh通用方法
computeV(img,px,key){
console.log("各种this",img,px,key);
percent = img / 100;
key = px / percent;
console.log("结果key",key);
return key;
},
//生成px通用方法
computeP(img,v){
temp = img / 100;
cache = temp * v;
console.log("缓存",cache);
return cache;
}
},
watch: {
pxWidth(val,oldVal){
//刚开始计算vw的写法
// vw = this.imgWidth / 100
// vwResult = this.pxWidth / vw;
// this.vwResult = vwResult;
//传过去的参数其实只是把数值传了过去,
//并没有把this.vwResult传过去,导致没有成功修改数据(小小问题困扰好久)
this.vwResult = app.computeV(this.imgWidth,this.pxWidth,this.vwResult);
//也可以用下面的方法写
// this.$options.methods.computeV(this.imgWidth,this.pxWidth,this.vwResult);
},
pxHeight(val,oldVal){
this.vhResult = app.computeV(this.imgHeight,this.pxHeight,this.vhResult);
},
vwResult(val,lodVal){
//刚开始计算px的写法
// vw = this.imgWidth / 100;
// pxWidth = vw * this.vwResult;
// if(this.pxWidth == pxWidth){
// console.log("相等的");
// }else{
// this.pxWidth = pxWidth;
// }
// this.pxWidth = app.computeP(this.imgWidth,this.vwResult,this.pxWidth);
//进行判断是为了解决重复赋值的问题
let temp = app.computeP(this.imgWidth,this.vwResult);
if(this.pxWidth == temp){
console.log("执行这里");
}else{
this.pxWidth = temp;
}
},
vhResult(val,lodVal){
let temp = app.computeP(this.imgHeight,this.vhResult);
if(this.pxHeight == temp){
console.log("执行这里");
}else{
this.pxHeight = temp;
}
}
}