You need to enable JavaScript to run this app. Vue.js中如何识别处于聚焦状态的input输入框并获取其值
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中如何识别处于聚焦状态的input输入框并获取其值

实现方案

核心逻辑是记录最后一次处于聚焦状态的输入框索引,点击打印按钮时直接取对应值即可,具体改动如下:

  1. 在data中新增activeInputIndex字段,用于存储当前/最后一次聚焦的输入框下标,默认值为-1(表示无聚焦输入框)
  2. 给每个input绑定@focus事件,触发时将当前输入框的下标赋值给activeInputIndex
  3. 给logActiveBox按钮绑定点击事件,判断activeInputIndex合法后打印对应输入框的值
  4. 补充修复原代码中el: app的语法错误,正确写法为el: '#app'

完整可运行代码

<div id="app">
  <br><br><br>
  <div v-for="(item,index) in items" :key="index">
    <!-- 新增@focus事件记录当前聚焦的输入框下标 -->
    <input type="text" v-model="items[index]" @focus="activeInputIndex = index">
    <button type="submit" @click.prevent="logThisBoxVal(index)">
      log this Box
    </button>
  </div>
  <br><br>
  <!-- 绑定点击事件 -->
  <button @click="logActiveBox">logActiveBox</button>
</div>

<script>
var application = new Vue({
  el: '#app', // 修复原代码的语法错误
  created() {

  },
  data() {
    return {
      items: [
        "box1", "box2"
      ],
      activeInputIndex: -1 // 新增存储聚焦下标字段
    };
  },
  methods: {
    logThisBoxVal(i) {
      console.log(this.items[i])
    },
    // 新增打印激活输入框值的方法
    logActiveBox() {
      if (this.activeInputIndex >= 0 && this.activeInputIndex < this.items.length) {
        console.log(this.items[this.activeInputIndex])
      } else {
        console.log('当前无聚焦的输入框')
      }
    }
  },
  computed: {

  },

})
</script>

可选极简方案(无需额外响应式变量)

如果不想新增数据字段,也可以直接通过浏览器原生API获取当前激活元素判断,需要额外处理按钮点击导致输入框失焦的问题,改动如下:

  1. 给按钮添加@mousedown.prevent阻止默认行为,避免点击时输入框失焦
  2. 方法内直接读取document.activeElement判断是否为目标输入框
<button @mousedown.prevent="logActiveBox">logActiveBox</button>
// 对应methods中的方法
logActiveBox() {
  const activeEl = document.activeElement
  if (activeEl.tagName === 'INPUT' && activeEl.closest('#app')) {
    console.log(activeEl.value)
  } else {
    console.log('当前无聚焦的输入框')
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 04:57:04