首先我们先来看下面这个示例:
html部分
<el-input ref="label" v-show="showLabel" v-model="ruleForm.label" @blur="btnBlur()" maxlength="5" show-word-limit ></el-input>
<i class="el-icon-plus" v-if="openlabel" @click="btnOpen"></i>
js部分
export default {
data() {
return {
showLabel:false
},
methods:{
当我点击btnOpen按钮的时候,我把input输入框显示出来,并自动获取焦点,但是input显示出来之后并没有自动获取到焦点,
原因是因为当我代码执行完this.$refs.label.focus()时dom还没来得及更新或者还在更新中,此时就自动获取焦点失败
知道了原因之后我们就可以使用this.$nextTick(()=>{})来处理,this.$nextTick()会等待下次dom更新循环之后执行,所以代码修改为
btnOpen(){
this.showLabel = true
this.$nextTick(()=>{
this.$refs.label.focus()
})
}
//错误写法
btnOpen(){
this.showLabel = true
this.$refs.label.focus()
}
}
}