Vue implements the component. After the property of the v-model binding is modified, the {{}} binding displays correctly, and the input box shows an error.

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>
Jul.06,2021

solution:

set(_val) {
      this.amount_ = this.autonumeric(_val)
      this.total_ = this.autonumeric(this.amount_ * this.rate)
      this.$forceUpdate()
}

reason:
when you enter 46.3346.333, 46.3333 in the input box, the values of this.total_ and this.amount_ do not change, so vue does not trigger rendering, which leads to the undercorrection of input.


add why the value of
has not changed. First of all, you have to understand the v-model syntax sugar. The appeal code v-model is equivalent to

.
 :<input type="text"  :value="total" @input="total = $event.target.value">{{ total }}<br /><br />

when the input event triggers set agent _ val=48.333 , the current this.total_=48.33 , then execute this.total_= this.autonumeric (this.amount_ * this.rate) / / 48.33 without changing the value and triggering no update. The input process is then triggered again to repeat the appeal process.

    this.total_ = _val;
    this.$nextTick(()=>{
          this.total_ = this.autonumeric(_val)
          this.amount_ = this.autonumeric(this.total_ / this.rate)
    })
Menu