今天接到一个需求,需要在一个输入框输入算式公式,然后需要在表单填写的时候使用该公式进行计算值,由于是公司的代码无法展示,下面做一个例子来重点说明new function的其中一种使用方式。
现在有几个输入框
现在想求出毛利,那么需要公式去计算
我们定义如下
将成本价设定为a,销售价为b,卖出数量为c,库存为d,进货数量为e
那么可以得出毛利公式为(bc)-(ae)
将公式写在下面的输入框里
这时候只要输入上面的值即可算出结果
这样做就可以实现上面的输入框为动态,下面计算公式也是动态,只要符合规定的规则去书写公式就可以实现动态计算,这个只是个例子,具体情况具体分析,我把代码放在下面
<template>
<div>
<div class="top">
<div>
<label>成本价</label>
<input type="number" @change="computer()" v-model="costPrice">
</div>
<div>
<label>销售价</label>
<input type="number" @change="computer()" v-model="salePrice">
</div>
<div>
<label>卖出数量</label>
<input type="number" @change="computer()" v-model="quantitysold">
</div>
<div>
<label>库存</label>
<input type="number" @change="computer()" v-model="inventory">
</div>
<div>
<label>进货数量</label>
<input type="number" @change="computer()" v-model="quantity">
</div>
<div>
<label>毛利</label>
<input type="number" v-model="grossmargin">
</div>
</div>
<div class="bottom">
<div>
<label>计算公式</label>
<input type="text" v-model="formula">
</div>
</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
},
data() {
return {
costPrice: "",
salePrice: "",
quantitysold: "",
inventory: "",
quantity: "",
grossmargin: "",
formula: "233",
}
},
methods:{
computer(){
console.log(this.formula)
let sum = new Function("a","b","c","d","e",`return ${this.formula}`);
this.grossmargin = sum(parseFloat(this.costPrice),parseFloat(this.salePrice),parseFloat(this.quantitysold),parseFloat(this.inventory),parseFloat(this.quantity))
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
.top {
/* display: flex; */
}
</style>
最重点的就是这行代码
new Function(“a”,“b”,“c”,“d”,“e”,
return ${this.formula}
);