【问题标题】:Vue.js circular computed propertiesVue.js 循环计算属性
【发布时间】:2017-10-06 22:58:16
【问题描述】:

我有一个应用程序需要更新两个相互依赖的字段的值。

例如:

<template>
    <tr>
        <td>{{total}}</td>
        <td><input type="text" v-model="calculateEarnedPercentage" @change="updatedForecastPercentage"></td>
        <td><input type="text" v-model="spent_dollar"></td>
    </tr>
</template>

<script>
    export default {
        data () {
            return {
                total: 1000000,
                spent_percentage: '',
                spent_dollar: 20000,
            }
        },
        methods: {
            updatedForecastPercentage () {
                this.vendor.regional_forecast_dollar = this.vendor.purchases / (this.vendor.regional_forecast_dollar / 100)
            }
        },
        computed: {
            calculateEarnedPercentage () {
                return (this.vendor.regional_forecast_dollar / this.vendor.purchases) * 100
            }
        }
    }
</script>

这两个“花费”值取决于静态“总”值。我将存储已花费的美元,百分比将由此得出。

现在如果用户更新百分比,我需要更新美元价值。 如果他们更新美元价值,我需要更新百分比。

到目前为止,它显然不起作用。正在进行循环更新。 您如何设计数据以在 Vue.js 中实现此功能?

【问题讨论】:

  • 一个是真实数据项,另一个是可写计算。
  • 如果你在做v-model="computed property",那么考虑为这个计算属性(set prop)定义一个setter。在此设置器中,您可以根据更改的结果值对变量应用一些逻辑。阅读:vuejs.org/v2/guide/computed.html#Computed-Setter
  • @wostex 谢谢!我不知道获取/设置动态。

标签: vue.js computed-properties datadesign


【解决方案1】:

看起来您可以使用一些手表和互斥锁。 从并行处理中获取一个想法,我构建了一个 JSfiddle 来展示这个想法

<div id="app">
  <span>{{ total }}</span>
  <span><input type="text" v-model.number.lazy="spent_percentage"></span>
  <span><input type="text" v-model.number.lazy="spent_dollar"></span>
  
  <pre>{{ $data }}</pre>
</div>
 new Vue({
      el: '#app',
      data () {
        return {
          total: 1000000,
          spent_percentage: 5.0,
          spent_dollar: 20000,
          mutex: false,
          vendor: {
            purchases: 2358,
            regional_forecast_dollar: 1
          }
        }
      },
      watch: {
        spent_percentage: function(value, old_value) {
          if (!this.mutex) {
            this.mutex = true
            
            this.spent_dollar = (this.vendor.purchases * value) / 100;
            this.spent_percentage = value;
        
            this.mutex = false
          }
        },
        spent_dollar: function(value, old_value) {
          if (!this.mutex) {
            this.mutex = true
            
            this.spent_dollar = value;
            this.spent_percentage = (value / this.vendor.purchases) * 100;
            
            this.mutex = false
          }
        }
      }
    })

【讨论】:

    猜你喜欢
    • 2017-08-26
    • 1970-01-01
    • 2019-08-08
    • 2017-10-07
    • 2021-03-01
    • 2018-09-09
    • 1970-01-01
    • 2016-09-17
    • 2017-08-31
    相关资源
    最近更新 更多