【问题标题】:Force re-compute to Vue computed property?强制重新计算到 Vue 计算属性?
【发布时间】:2018-11-03 00:22:52
【问题描述】:

是否可以在 vue 中重新计算计算属性?我有一个简单的订单项总计(价格 x 数量)。如果选中该框并且输入值发生更改,则重新计算属性。如果我取消选中该框,则计算的属性仍然存在。我想要的行为是将显示的值重置为 0。我在考虑添加一个隐藏值,将复选框切换设置为 1 或 0,然后将其添加到乘法中 - 即 this.line_units * this.line_rate * this.is_toggled ,但它似乎有点hacky。有人有更好的方法吗?

<template>
<tr :class="{ 'row-disabled': !enabled }">
    <td><input type="checkbox" @change="toggle" :value="checkbox" class="form-check-input" :checked="enabled"></td>
    <td>{{ description }}</td>
    <td><input type="number" min="0" @change="setLineUnits" :value="line_units" class="form-control" :disabled="!enabled"></td>
    <td><input type="number" min="0" @change="setLineRate" :value="line_rate" class="form-control" :disabled="!enabled"></td>
    <td>${{ total.toFixed(2) }}</td>
</tr>
</template>
<style lang="scss">
.row-disabled {
background: #ddd;
color: #555;
}
</style>
<script>
export default {
data() {
    return {

    };
},
computed: {
    total: {
        cache: false,
        get: function() {
            if (this.enabled) {
                return this.line_units * this.line_rate;
            } else return 0;
        }
    }
},
methods: {
    toggle() {
        this.$emit('lineInput', {
            enabled: !this.enabled
        })
    },
    setLineUnits(evt) {
        this.$emit('lineInput', {
            line_units: Number(evt.target.value)
        })
    },
    setLineRate(evt) {
        this.$emit('lineInput', {
            line_rate: Number(evt.target.value)
        })
    }
},
props: {
    enabled: {
        type: Boolean,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    line_rate: {
        type: Number,
        required: true
    },
    line_units: {
        type: Number,
        required: true
    }
}
}
</script>

【问题讨论】:

  • 尝试使用v-model 而不是:value

标签: vuejs2


【解决方案1】:

您没有更改任何值,因此不会触发 @changed 事件。 enabled 未绑定到输入,:changed/:value 属性仅绑定一种方式。

我建议使用@click,除非您有其他原因不想这样做。

【讨论】:

    猜你喜欢
    • 2020-12-10
    • 1970-01-01
    • 2019-10-25
    • 2020-11-27
    • 2020-02-03
    • 2014-04-17
    • 2019-10-03
    • 1970-01-01
    • 2015-01-28
    相关资源
    最近更新 更多