概念:
1.在表单的提交按钮上添加 Vue 原生属性 native-type="submit" 可以让按钮变为表单提交按钮;
2.阻止表单默认提交事件(默认是阻止),在表单上(即<el-form>标签上)添加 @submit.native.prevent 即可
3.因为el-form默认不支持表单回车提交,在表单上(即<el-form>标签上)添加@keyup.enter.native="submitForm('form')"可实现回车提交表单
template:
<el-form ref="form" :model="form" :rules="rules" @keyup.enter.native="submitForm('form')">
<el-form-item label="" prop="username">
<el-input prefix-icon="el-icon-user-solid" placeholder="请输入用户名" v-model="form.username" clearable></el-input>
</el-form-item>
<el-form-item label="" prop="password">
<el-input prefix-icon="el-icon-lock" placeholder="请输入密码" v-model="form.password" show-password clearable></el-input>
</el-form-item>
<el-button class="button" type="primary" @click="submitForm('form')">登录</el-button>
</el-form>
script:
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
// console.log(this.form);
this.$axios.post('login', this.form).then((response) => {
console.log(response);
this.$message({
message: '登陆成功',
type: 'success'
});
localStorage.setItem('token', response.data.access_token); //本地存储token值
// console.log(localStorage.getItem('token'));
this.$router.push({
path: '/',
})
}).catch((error) => {
this.$message({
message: '账号或密码错误',
type: 'error'
});
});
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
},
created() {
this.token = localStorage.getItem('token'); //在登录页面验证成功而保存的token值,进行获取
if (this.token) { //若this.token存在
this.$router.push({path:'/'})
}
}
}
说明:
1、转载地址:
https://blog.csdn.net/qq_28137309/article/details/103418726
2、回车第一次页面刷新:@submit.native.prevent