Vue如何在输入框显示星号掩码时获取用户输入的真实值
问题原因
你的现有代码存在逻辑循环:输入框绑定的是替换后的星号掩码值,输入事件触发时拿到的target.value本身就已经是掩码内容,将这个值赋值给存储变量自然无法获取原始输入。
修复后完整代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vue 输入掩码</title> </head> <body> <div id="app"> <div> Input : <input type="text" class="form-control" name="sector" id="sector" required @input="onInput" /> <br> 原始输入值:{{ rawValue }} </div> </div> <script src="https://unpkg.com/vue"></script> <script> const app = new Vue({ el: "#app", data() { return { rawValue: '', // 存储用户真实原始输入 lastMaskedValue: '' // 记录上一次的掩码值,用于比对输入变化 } }, methods: { onInput(e) { const inputEl = e.target const currentInputVal = inputEl.value const cursorPos = inputEl.selectionStart // 记录当前光标位置 // 处理输入/删除逻辑 if (currentInputVal.length > this.lastMaskedValue.length) { // 新增输入:找到新增的字符插入到原始值对应位置 let insertChar = '' let insertIndex = 0 for (let i = 0; i < currentInputVal.length; i++) { if (currentInputVal[i] !== this.lastMaskedValue[i]) { insertChar = currentInputVal[i] insertIndex = i break } } this.rawValue = this.rawValue.slice(0, insertIndex) + insertChar + this.rawValue.slice(insertIndex) } else if (currentInputVal.length < this.lastMaskedValue.length) { // 删除内容:从原始值对应位置删除字符 const deleteLength = this.lastMaskedValue.length - currentInputVal.length this.rawValue = this.rawValue.slice(0, cursorPos) + this.rawValue.slice(cursorPos + deleteLength) } // 生成新的掩码值:仅数字替换为星号,其他字符保留 const newMaskedVal = this.rawValue.replace(/\d/g, '*') this.lastMaskedValue = newMaskedVal // 回填掩码值到输入框,恢复光标位置 inputEl.value = newMaskedVal inputEl.selectionStart = inputEl.selectionEnd = cursorPos } } }) </script> </body> </html>
核心改动说明
- 新增独立的
rawValue变量存储真实输入,和掩码展示逻辑完全解耦,不会被星号内容覆盖 - 输入时先比对上一次掩码值和当前输入框内容,计算出用户实际输入的原始字符更新到
rawValue - 自动处理光标位置,避免输入过程中光标自动跳到末尾的体验问题
- 保留原需求的分隔符规则,仅替换数字为星号,
-等特殊字符会原样展示在掩码中
内容的提问来源于stack exchange,提问作者user16583522
相关产品推荐
相关产品推荐

