vue.js - 如何知道 vue.js 中哪个输入是焦点?

标签 vue.js vuejs2

在下面的示例中,可以使用两个按钮轻松记录 inputBox 的值(我知道这一部分)。但还有第三个按钮,其作用是记录处于焦点/事件状态的 inputBox 的值。在 vue.js 中如何做到这一点

<div id="app">
    <br><br><br>
      <div v-for="(item,index) in items" :key="index">
        <input type="text" v-model="items[index]" >
        <button type="submit" @click.prevent="logThisBoxVal(index)">
          log this Box
        </button>
      </div>
      <!-- ToDo -->
      <br><br>
      <button>logActiveBox</button>
  </div>

<script>
    var application = new Vue({
      el: app,
      created() {

      },
      data() {
        return {
          items: [
            "box1", "box2"
          ]
        };
      },
      methods: {
        logThisBoxVal(i) {
          console.log(this.items[i])
        }
      },
      computed: {

      },

    })
  </script>

最佳答案

一种方法是向输入添加一个焦点事件,将其定义为事件状态,然后使用该事件在单击 logActiveBox 按钮时选择要 console.log 的事件,如果未选择任何事件,则不输出到控制台。不知道为什么你需要这个。

var application = new Vue({
  el: '#app',
  data() {
    return {
      active: null,
      items: [
        "box1", "box2"
      ]
    };
  },
  methods: {
    logThisBoxVal(i) {
      this.active = typeof i !== 'undefined' ? i : this.active
      if (this.active !== null) {
        console.log(this.items[this.active])
      }
    }
  }
})
/* ignore - used to reduce SO's console output */

.as-console-wrapper {
  height: 20px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.js"></script>

<div id="app">
  <div v-for="(item,index) in items" :key="index">
    <input type="text" v-model="items[index]" @focus="active = index">
    <button type="submit" @click.prevent="logThisBoxVal(index)">
       log this Box
    </button>
  </div>
  <button @click="logThisBoxVal()">logActiveBox</button>
</div>

关于vue.js - 如何知道 vue.js 中哪个输入是焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67594409/

相关文章:

javascript - 使用文件输入预览在 v-for 循环中添加/删除行

vue.js - 如何在 vue.js 2 的其他组件中调用方法?

javascript - HTML 实体到 Unicode 转义序列

vue.js - 在列表中编辑记录,使用 VueJS 动态定义子属性

javascript - VueJS 数据属性在已安装函数中返回未定义

vue.js - Vue 2.0 组件 - 无法呈现模板中的所有 <div>

firebase - Vuex,在 Action 中改变状态

vue.js - 在提交时获取表单数据?

vue.js - 如何在 Action 中触发 js-vue-modal

vue.js - 在axios中重写jquery ajax请求并设置xhrFields