You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vuetify 2 + Vue.js 2:文本框无法获取真实输入值问题

问题根源

你的代码逻辑错误在于**@input事件触发时,displayInput已经被Vue的v-model更新为用户输入字符与之前替换文本的混合值**,而非用户的原始输入内容。

举个输入"jump"的过程示例:

  1. 输入第一个字符"j" → displayInput变为"j" → 被push到userInput → 随后被替换为"T"
  2. 输入第二个字符"u" → v-model自动合并之前的"T"和新输入的"u",displayInput变为"Tu" → 被push到userInput → 随后被替换为"Th"
  3. 输入第三个字符"m" → displayInput变为"Thm" → 被push到userInput → 随后被替换为"Thi"
  4. 输入第四个字符"p" → displayInput变为"Thip" → 被push到userInput → 随后被替换为"This"

最终userInput的最后一项是"Thip",这就是点击Show后显示错误结果的原因。

解决方案

我们需要将用户原始输入和显示文本彻底分离:用单独变量存储用户输入,displayInput只负责展示自动替换后的内容,同时通过键盘事件捕获原始输入,避免v-model的自动合并干扰。

修改后的完整代码如下:

JS代码

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      automaticWord: "This is automatic word. Any letters or character type in textfield will be replaced by this sentence.",
      userInput: "", // 存储用户原始输入的完整内容
      displayInput: "",
      result: '',
    }
  },
  methods:{
    handleKeydown(e) {
      // 处理可打印字符输入
      if (e.key.length === 1 && !e.ctrlKey && !e.metaKey) {
        this.userInput += e.key;
        this.displayInput = this.automaticWord.slice(0, this.userInput.length);
        e.preventDefault(); // 阻止默认输入,避免字符直接显示
      } 
      // 处理退格删除
      else if (e.key === 'Backspace') {
        this.userInput = this.userInput.slice(0, -1);
        this.displayInput = this.automaticWord.slice(0, this.userInput.length);
        e.preventDefault();
      }
    },
    handlePaste(e) {
      // 处理粘贴事件,捕获粘贴的文本
      const pastedText = e.clipboardData.getData('text');
      this.userInput += pastedText;
      this.displayInput = this.automaticWord.slice(0, this.userInput.length);
      e.preventDefault();
    },
    showResult() {
      this.result = this.userInput;
    },
  },
})

HTML代码

<link rel="stylesheet" href="https://unpkg.com/vuetify@2.7.1/dist/vuetify.min.css">
<script src="https://unpkg.com/vue@2.x/dist/vue.js"></script>
<script src="https://unpkg.com/vuetify@2.7.1/dist/vuetify.min.js"></script>

<div id="app">
  <v-app id="inspire">
    <div class="text-center">
      <v-container fluid>
        <v-text-field
          label="Type here"
          v-model="displayInput"
          @keydown="handleKeydown"
          @paste="handlePaste"
        ></v-text-field>
        <v-btn color="primary" @click="showResult">Show</v-btn>
        <div class="ma-3">
            Result: <span class="text-h6 red--text">{{ result }}</span>
        </div>
    </v-container>
    </div>
  </v-app>
</div>

代码说明

  • userInput专门存储用户输入的所有原始内容,包括键盘输入和粘贴的文本
  • 通过@keydown捕获键盘输入,判断是否为可打印字符或退格键,更新userInput后同步替换displayInput,并阻止默认输入行为避免字符直接显示
  • 新增@paste处理粘贴场景,确保粘贴的文本也能被正确记录
  • showResult直接读取userInput即可得到用户的真实输入内容

内容的提问来源于stack exchange,提问作者Keyboard Corporation

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 22:50:07