Element UI输入框focus()方法自动获取焦点失败处理方法

Element UI输入框focus()方法自动获取焦点失败处理方法

​ 本来想通过自定义事件触发输入框,并获取焦点,但是使用官方提示的focus()方法一直失效

后来百度了半天,终于找到一个比较好的处理方法。

在这里插入图片描述

先放对比代码:

  • 刚开始的代码
<el-input
    v-if="isFormOpened"
    v-model="scope.row.name"
    @blur="updateLib">
</el-input>

<el-button 
    type="primary"
    @click="openUpdateForm">
</el-button>


//触发方法
openUpdateForm(){
            this.isFormOpened = true
            this.$refs.inputRef.focus()
        },
  • 后来修改后的代码
<el-input
    v-if="isFormOpened"
    v-model="scope.row.name"
    ref="inputRef"
    @blur="updateLib(scope.row.id,scope.row.name)">
</el-input>

<el-button 
    type="primary"
    @click="openUpdateForm(scope.row.name)">
</el-button>


//触发方法
openUpdateForm(){
            this.isFormOpened = true
            setTimeout(()=>{
                this.$refs.inputRef.focus()
            },0)
        },

完美解决
在这里插入图片描述

总结:

百度查了半天,终于找到了原因

  • 问题原因:渲染组件需要时间,并且时间没有JS执行的快;所以获取不到

  • 解决办法:

    • 第一种利用setTimeout ,也就是我上面使用的方法
     setTimeout(()=>{
       this.$refs.input1.focus();
    },0)
    
    • 第二种:利用 this.$nextTick (Dom更新完毕再执行回调函数)
    this.$nextTick(()=>{
        this.$refs.input1.focus();
    })
    

PS:转载请标明出处!

  • 15
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值