1、需要聚焦的el-input输入框设置ref值: ref="getfcous"
<el-input v-model="workorder" ref="getfocus" :clearable="true" @keyup.enter.native="fill()" placeholder="请扫码或输入"/>
2、在mounted生命周期使用this.$nextTick设置自动聚焦:
mounted(){
// 页面渲染完成时自动聚焦到用户名输入框,ref="getfocus"
this.$nextTick(() => {
this.$refs.getfocus.focus();
})
},
=============================================================================================
此处表单使用element-plus框架中的表单组件。
制作简单版的登录表单。
2个输入框:用户名username,密码password;1个登录按钮。
表单中双向绑定:
data中设置对象user来获取并保存表单中输入的数据:user:{username:'',password:''}。
el-form标签: :model="user"
el-input输入框: v-model="user.username"和v-model="user.password"
加载页面时输入框自动聚焦:
1. 需要聚焦的el-input输入框设置ref值: ref="unameInput" (unameInput为自己任意命名)
2. 在mounted生命周期使用this.$nextTick设置自动聚焦:
mounted(){
// 页面渲染完成时自动聚焦到用户名输入框,ref="unameInput"
this.$nextTick(() => {
this.$refs.unameInput.focus();
})
}
回车自动聚焦下一个输入框:
1. 先在需要聚焦的el-input输入框上设置ref值:ref="pwdInput"。
2. 再用@keyup.enter设置回车自动聚焦:
回车聚焦下一个输入框:@keyup.enter="this.$refs['pwdInput'].focus()"
回车聚焦到登录按钮:@keyup.enter="login('form')"
登录按钮(此处方法login):@click="login('former')"
完整代码:
<template>
<div class="login">
<el-form
label-position="top"
label-width="100px"
:model="user"
style="max-width: 460px"
>
<el-form-item label="用户名:">
<el-input
v-model="user.username"
ref="unameInput"
@keyup.enter="this.$refs['pwdInput'].focus()"/>
</el-form-item>
<el-form-item label="密码">
<el-input type="password"
v-model="user.password"
ref="pwdInput"
@keyup.enter="login('form')"/>
</el-form-item>
<el-button type="primary"
@click="login('former')"
>
登录
</el-button>
</el-form>
</div>
</template>
<script>
export default {
name:'login',
data(){
return{
user:{username:'',password:''},
userList:[
{username:'admin',password:'123'},
{username:'11',password:'11'}
]
}
},
mounted(){
// 页面渲染完成时自动聚焦到用户名输入框,ref="unameInput"
this.$nextTick(() => {
this.$refs.unameInput.focus();
})
},
methods:{
// 登录
login(){
try{
this.userList.forEach((u) => {
if(u.username === this.user.username && u.password === this.user.password){
this.$router.push('/');
throw new Error('已匹配')
}
})
}catch(e){
return
};
alert("请输入正确用户名和密码。")
}
}
}
</script>
<style>
.login{
/* 表单外容器样式 */
background:rgb(245, 240, 240);
height:320px;
width:450px;
margin:100px auto;
border-radius: 20px;
/* 表单位置水平垂直居中 */
display:flex;
justify-content: center;
align-items: center;
}
</style>