使用ElementUI完成登入注册的跨域请求提高开发效率
在使用ElementUI进行登录注册的跨域请求时,我们可以利用ElementUI的表单验证功能和Axios进行HTTP请求。以下是一个简单的例子:
首先,安装axios:
npm install axios
然后,使用ElementUI构建登录和注册表单,并使用axios发送跨域请求。
登录表单代码示例:
<template>
<el-form :model="loginForm" :rules="loginRules" ref="loginForm">
<el-form-item prop="username">
<el-input v-model="loginForm.username" placeholder="Username"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input type="password" v-model="loginForm.password" placeholder="Password"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitLogin">Login</el-button>
</el-form-item>
</el-form>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
loginForm: {
username: '',
password: ''
},
loginRules: {
username: [
{ required: true, message: 'Please input username', trigger: 'blur' }
],
password: [
{ required: true, message: 'Please input password', trigger: 'blur' },
{ min: 6, message: 'Password length should be greater than 6', trigger: 'blur' }
]
}
};
},
methods: {
submitLogin() {
this.$refs.loginForm.validate(valid => {
if (valid) {
axios.post('http://example.com/api/login', this.loginForm)
.then(response => {
// Handle login success
console.log(response.data);
})
.catch(error => {
// Handle login error
console.error(error);
});
} else {
console.log('Login form is not valid');
return false;
}
});
}
}
};
</script>
注册表单代码示例:
<template>
<el-form :model="registerForm" :rules="registerRules" ref="registerForm">
<el-form-item prop="username">
<el-input v-model="registerForm.username" placeholder="Username"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input type="password" v-model="registerForm.password" placeholder="Password"></el-input>
</el-form-item>
<el-form-item prop="email">
<el-input v-model="registerForm.email" placeholder="Email"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitRegister">Register</el-button>
</el-form-item>
</el-form>
</temp
评论已关闭