elementui中手动使输入框聚焦

388 阅读1分钟

方法一、绑定ref

<el-input v-model="form.name" ref="name"></el-input>
this.$refs.name.focus();

方法二、通过自定义事件中的事件对象 $event,找到input

<el-input v-model="form.name" ref="name" @key.enter.native="inputFocus($event)"></el-input>

inputFocus(e){
	e.target.focus();
	e.target.blur(); //让输入框失去焦点
}

方法三、使用自定义指令

<el-input v-model="form.name" ref="name" v-focus></el-input>

directives: {
    focus: {
        inserted: function (el) {
        	console.log(el);
        	//因为el-input这是个组件,input外面被一层 div 包裹着
        	//el打印出来是外面这个 div,需要找到内层的input
        	el.children[1].focus();
        }
    }
}

方法四、使用原生input

<input type="text" id="userName" name="username" autofocus="autofocus"/>

this.$nextTick(()=>{
	var userName = document.getElementById("userName");
	userName.focus();
})