el-input设置自动聚焦this.$refs.xxx.focus is not a function报错

碰到一个需求,在<el-input ref="promptInput" type="textarea">中,使用

this.$nextTick(() => {
this.$ref.promptInput.focus();
});

出现了报错。

具体报错为

this.$refs.promptInput.focus is not a function

打印一下this.$refs.promptInput发现有值,但是找不到focus方法

问题在于直接给el-input绑定一个ref取到的是textarea外面的那层div
并没有真正的拿到textarea

分析一下 this.$refs.promptInput 的打印值,外面的那层div只有change,input,blur方法,focus是直接绑在textarea上面的

实测正确的写法为:

this.$nextTick(() => {
            this.$refs?.promptInput?.$children[0]?.$refs?.textarea?.focus();
        });

或者更简单一点:

this.$nextTick(() => {
                 this.$refs?.promptInput?.$children[0]?.focus();
             });

另一种写法,直接用querySelector,不用ref

this.$nextTick(() => {
                        document.querySelector('textarea').focus();
                    });

如果有多个

this.$nextTick(() => {
                        document.querySelectorAll('textarea')[1].focus();
                    });
  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值