首页 > 解决方案 > 如何在按键上获取当前值

问题描述

我正在使用 vue.js 并在表内创建一个表我有一个输入字段,quantity所以当我输入第一个单词时它正在empty控制台上打印

假设我正在输入 3,然后显示为空,如果我正在输入 44,那么它会打印 4,我正在使用v-on:keypress我不知道这里出了什么问题来捕获事件

var app = new Vue({
  el: "#app",
  data: {

    invoice_products: [{
      product_no: '',
      product_name: '',
      product_price: '',
      product_qty: '',
      line_total: 0
    }]
  },

  methods: {
    calculateLineTotal(invoice_product) {
      console.log(invoice_product.product_qty)
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.6/vue.js"></script>
<div id="app">

  <table>
    <thead>
      <tr>

        <th>Quantity</th>
        
      </tr>
    </thead>
    <tbody>
      <tr v-for="(invoice_product, k) in invoice_products" :key="k">

        <td>
          <input class="form-control text-right" type="number" min="0" step=".01" v-model="invoice_product.product_qty" v-on:keypress="calculateLineTotal(invoice_product)" />
        </td>

      </tr>
    </tbody>
  </table>
</div>

标签: javascriptvue.js

解决方案


You should use keyup event handler.

KeyPress, KeyUp and KeyDown are analogous to, respectively: Click, MouseUp, and MouseDown.

  1. Down happens first
  2. Press happens second (when text is entered)
  3. Up happens last (when text input is complete).

var app = new Vue({
  el: "#app",
  data: {

    invoice_products: [{
      product_no: '',
      product_name: '',
      product_price: '',
      product_qty: '',
      line_total: 0
    }]
  },

  methods: {
    calculateLineTotal(invoice_product) {
      console.log(invoice_product.product_qty)
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.6/vue.js"></script>
<div id="app">

  <table>
    <thead>
      <tr>

        <th>Quantity</th>
        
      </tr>
    </thead>
    <tbody>
      <tr v-for="(invoice_product, k) in invoice_products" :key="k">

        <td>
          <input class="form-control text-right" type="number" min="0" step=".01" v-model="invoice_product.product_qty" v-on:keyup="calculateLineTotal(invoice_product)" />
        </td>

      </tr>
    </tbody>
  </table>
</div>


推荐阅读