Vue JS技术需求:实现输入框失焦时触发单次数据库保存
Got it, let's tackle this issue where your updateItemQuantity method fires every time the user types a single character. The root cause is using the input event, which triggers immediately with each keystroke. We need to switch to the blur event (which fires when the input loses focus) to ensure the database only updates once the user finishes entering their desired quantity.
Here's the revised code:
1. Update the Product Counter Component
We'll replace the input event with blur, and rename the emitted event for better clarity:
Vue.component('product-counter', { props: ['quantity'], data: function () { return { count: this.quantity } }, template: ` <div class="input-group"> <input v-bind:value="quantity" v-on:blur="$emit('update-quantity', $event.target.value)" type="text" class="form-control col-2" > </div> ` })
Renaming the event to update-quantity makes it obvious what the event is intended to do, avoiding confusion with the default input event.
2. Adjust the Component Call
Update the event listener to match our new update-quantity event:
<product-counter v-bind:productcode="item.productCode" v-bind:quantity="item.quan" v-on:update-quantity="item.quan = updateItemQuantity($event, item.productCode)" v-on:increment-quantity="item.quan = updateItemQuantity(item.quan, item.productCode)" v-on:decrement-quantity="item.quan = updateItemQuantity(item.quan, item.productCode)" ></product-counter>
3. Keep Your updateItemQuantity Method As-Is
Your existing logic doesn't need changes—it will now only run once per input session, when the user finishes typing and clicks away or tabs out of the field:
"updateItemQuantity": function (totalquantity, pcode) { if (totalquantity != '') { // ... Your database update logic here ... } }
Why This Works:
- The
blurevent triggers only when the input loses focus, so even if the user types "123", the method will fire just once with the final value "123". - The renamed event makes your code more maintainable, so other developers (or future you) can quickly understand the event's purpose.
If you want to add extra validation (like ensuring the input is a valid number), you could add that inside the component before emitting the value—but the core fix here is switching the event from input to blur.
内容的提问来源于stack exchange,提问作者AliAzra

