【发布时间】: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