vue实现组件,v-model绑定的属性修改后,{{}}绑定显示正确,输入框显示错误

发布于 2022-09-07 23:02:56 字数 1705 浏览 15 评论 0

写了一个自己计算的组件,已知条件为单价,输入金额,自动计算数量;输入数量,自动计算单价,但是金额和数量都要保留2位小数,我通过 replace 来实现。

图片描述

代码如下:

<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 #333
}
</style>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

幻想少年梦 2022-09-14 23:02:56

补充楼上
为什么说值没有更改,首先得理解v-model语法糖,上诉代码v-model等价于

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

input事件触发set代理_val=48.333的时候,当前this.total_=48.33,之后执行this.total_ = this.autonumeric(this.amount_ * this.rate)//48.33,值没有更改,不触发更新。此后重新触发input流程重复上诉过程。

    this.total_ = _val;
    this.$nextTick(()=>{
          this.total_ = this.autonumeric(_val)
          this.amount_ = this.autonumeric(this.total_ / this.rate)
    })
转角预定愛 2022-09-14 23:02:56

解决方案:

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

原因:
当你在输入框输入 46.33, 46.333, 46.3333 时, this.total_ 和 this.amount_ 的值都是没有变化的, 所以 vue 不会触发渲染, 这导致了 input 的值得不到矫正.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文