1

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

例如:

<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 中实现此功能?

4

1 回答 1

2

看起来你可以使用一些手表和互斥锁。从并行处理中获取一个想法,我构建了一个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-05-09T17:56:24.087 回答