在vuejs中观察动态变化对象的变化

Watching for changes in dynamically changing objects in vuejs

我正在尝试观察 "item.amount" v-model 的变化,并在每 1000 个之后添加逗号。问题是 v-model 是一个对象项,因此我无法使用 watch 方法直接访问它。我的代码如下所示:

<div class="row" v-for="(item,index) in Payments" :key="index">
  <input type="text" v-model="item.amount" placeholder="Amount" class="typeahead form-control-sm">
  <input class="typeahead form-control-sm" type="number" placeholder="Destination number" max="9999999999" min="0" onKeyDown="if(this.value.length==10 && event.keyCode>47 && event.keyCode < 58)return false;" v-model="item.Number" />
</div>

我怎样才能观察到 item.amount 的变化,这样我就可以在用户输入数量 时使用 String(item.amount).replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");[ 之类的东西来格式化输出=12=]

尝试将格式放在方法中。即,

methods: {
  formatNumber: function(x){
    String(x).replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }
}

然后这样输出;

{{formatNumber(item.amount)}}

或者;

:value="formatNumber(item.amount)"

我认为您需要通过 onType 方法处理 @input 事件来观察变化,该方法采用当前项目的 index 并在 Payments 中进行更改数组

new Vue({
  el: '#app',
  data: {
    Payments: [{
        "amount": 1122

      },
      {
        "amount": 8852

      },
      {
        "amount": 75553

      }
    ]
  },
  methods: {
    onType(i) {
      this.Payments[i].amount = String(this.Payments[i].amount).replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    }
  },
  mounted() {
    for (let i = 0; i < this.Payments.length; i++)
      this.onType(i)
  }

})
body {
  padding: 20px;
}
<!DOCTYPE html>
<html>

<head>
  <meta name="description" content="Vue.delete">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.min.js"></script>
</head>

<body>
  <div id="app">
    <div class="row" v-for="(item,index) in Payments" :key="index">
      <input type="text" v-model="item.amount" @input="onType(index)" placeholder="Amount" class="typeahead form-control-sm">
      <input class="typeahead form-control-sm" type="number" placeholder="Destination number" max="9999999999" min="0" onKeyDown="if(this.value.length==10 && event.keyCode>47 && event.keyCode < 58)return false;" v-model="item.Number" />
    </div>

编辑

如果输入已预填充,则可以在安装的挂钩中更改值