wrote a self-calculated component, knowing that the condition is the unit price, enter the amount, automatically calculate the quantity; enter the quantity, automatically calculate the unit price, but the amount and quantity have to retain 2 decimal places, I use replace to achieve.
the code is as follows:
<template>
<div>
:<span>{{ rate }}</span><br /><br />
:<input type="text" v-model="total">{{ total }}<br /><br />
:<input type="text" v-model="amount">{{ amount }}<br /><br />
</div>
</template>
<script>
export default {
name: "demo",
data() {
return {
rate: 0.5,
total_: "",
amount_: ""
}
},
methods: {
autonumeric(str) {
if (str == undefined) {
return ""
}
str = str.toString();
str = str.replace(/^(\-)*(\d+)\.(\d{0,2}).*$/, "$1$2.$3");
return str;
}
},
computed: {
total: {
get() {
return this.total_
},
set(_val) {
this.total_ = this.autonumeric(_val)
this.amount_ = this.autonumeric(this.total_ / this.rate)
}
},
amount: {
get() {
return this.amount_
},
set(_val) {
this.amount_ = this.autonumeric(_val)
this.total_ = this.autonumeric(this.amount_ * this.rate)
}
}
}
}
</script>
<style lang="stylus" scoped>
div{
width 300px
margin-left auto
margin-right auto
margin-top 100px
margin-left 100px
}
input{
border 1px solid -sharp333
}
</style>