input 自动获取焦点

问题描述:项目中一个需求,写了一个span显示,一个input隐藏,鼠标点击span后,span隐藏,input显示并获取焦点。

方法一:

// 注册一个全局自定义指令
Vue.directive('focus', {
  // When the bound element is inserted into the DOM...
  inserted(el) {
    // Focus the element
    el.querySelector('input').focus();
  },
});

使用用例:
<el-input v-focus></el-input>

方法二:

直接在页面中操作:

1)<el-input ref="input"></el-input>

2)在触发的方法中执行 this.$refs.input.focus();

/ ************** v-for ***************/

3)<div v-for="(task, index) in tasks">
    <el-input :ref="'select' + index"></el-input>
   </div>

注意:若input是在v-for中渲染得到的,
直接执行 this.$refs.input.focus();可能会报错,
可以在nextTick方法中执行,nextTick里面的代码会在DOM更新后执行。如下:

4)this.$nextTick(() => {
      this.$refs[`input${index}`][0].focus();
   });
原文地址:https://www.cnblogs.com/lynnekanuo/p/10175110.html