VueJS自定义货币掩码焦点切换时逗号位置偏移求助
Fix for VueJS Custom Currency Mask Shifted Comma Issue
The issue you're facing—where the comma shifts left when tabbing away or losing focus—stems from two key problems:
- A conflict between manual input value manipulation and Vue's
v-modeltwo-way binding - A regex pattern that formats numbers from left to right instead of right to left, leading to inconsistent formatting when values are reprocessed
Here's how to fix it:
Step 1: Update the Formatting Logic
Replace your formatCurrency method with this improved version that:
- Cleans the input value properly
- Uses a regex that adds commas from right to left (the standard for currency formatting)
- Updates the
initialBalancedirectly instead of manipulating the input element's value (avoids conflicts withv-model)
formatCurrency() { // Get the raw value and clean it: keep only digits and a single decimal point let rawValue = this.initialBalance.toString().replace(/[^\d.]/g, ''); // Split into integer and decimal parts const [integerPart, decimalPart] = rawValue.split('.'); // Format the integer part with commas (right to left) const formattedInteger = integerPart.replace(/(\d)(?=(\d{3})+$)/g, '$1,'); // Combine with decimal part (limit to 2 digits for currency) let formattedValue = formattedInteger; if (decimalPart) { formattedValue += `.${decimalPart.substring(0, 2)}`; } // Update the v-model bound value this.initialBalance = formattedValue; }
Step 2: Fix Event Binding
Instead of only binding to @keyup, add events for blur and paste to ensure formatting triggers in all scenarios. Also, remove the manual value manipulation from the template:
<v-text-field @keyup="formatCurrency" @blur="formatCurrency" @paste="formatCurrency" :prefix="currency" v-model="initialBalance" label="Balance" :disabled="disabled" ></v-text-field>
Why This Works:
- No more v-model conflicts: By updating
initialBalancedirectly, Vue handles syncing the value to the input field automatically. - Right-to-left formatting: The regex
/(\d)(?=(\d{3})+$)/gmatches digits that are followed by groups of three digits (at the end of the string), ensuring commas are placed correctly (e.g., 10000 → 10,000; 1000000 → 1,000,000). - Comprehensive event coverage:
keyuphandles real-time typing,blurfixes formatting when the input loses focus, andpasteensures pasted values are formatted immediately.
Additional Notes:
- If you need to handle negative values, adjust the cleaning regex to allow a leading minus sign:
replace(/[^\d.-]/g, '')and ensure the minus sign stays at the start of the formatted string. - For better performance, you could add a debounce to the
keyupevent to avoid running the format function on every single keystroke.
内容的提问来源于stack exchange,提问作者Veer3383
相关产品推荐
相关产品推荐

