springboot整合vue-element-template 实现登录
时间: 2023-10-23 07:24:25 浏览: 123
首先需要安装好SpringBoot和Vue,然后按照以下步骤整合vue-element-template实现登录功能:
1. 在vue-element-template中的src/api目录下新建一个user.js文件,用于定义登录接口:
```
import request from '@/utils/request'
export function login(username, password) {
return request({
url: '/login',
method: 'post',
data: {
username,
password
}
})
}
```
2. 在vue-element-template中的src/views/login目录下新建一个index.vue文件,用于实现登录页面:
```
<template>
<div class="login-container">
<div class="login-box">
<h2>登录</h2>
<el-form ref="form" :model="form" :rules="rules" label-position="left" label-width="80px" class="login-form">
<el-form-item label="用户名" prop="username">
<el-input v-model="form.username"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input type="password" v-model="form.password"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">登录</el-button>
</el-form-item>
</el-form>
</div>
</div>
</template>
<script>
import { login } from '@/api/user'
export default {
name: 'Login',
data() {
return {
form: {
username: '',
password: ''
},
rules: {
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}
}
},
methods: {
submitForm() {
this.$refs.form.validate(valid => {
if (valid) {
login(this.form.username, this.form.password).then(response => {
if (response.data.code === 0) {
this.$message.success('登录成功')
this.$router.push('/')
} else {
this.$message.error(response.data.msg)
}
}).catch(error => {
console.log(error)
})
} else {
return false
}
})
}
}
}
</script>
<style scoped>
.login-container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.login-box {
width: 400px;
height: 400px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
border-radius: 4px;
padding: 20px;
}
.login-form {
margin-top: 20px;
}
</style>
```
3. 在SpringBoot中的controller中定义/login接口,用于处理登录请求:
```
@RestController
public class UserController {
@PostMapping("/login")
public Result login(@RequestBody User user) {
// 验证用户名和密码
if ("admin".equals(user.getUsername()) && "123456".equals(user.getPassword())) {
return Result.ok();
} else {
return Result.error("用户名或密码错误");
}
}
}
```
4. 在SpringBoot中的application.properties中配置跨域访问:
```
# 允许跨域访问
spring.mvc.cors.allow-credentials=true
spring.mvc.cors.allowed-origins=*
spring.mvc.cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS
spring.mvc.cors.allowed-headers=*
```
这样就实现了SpringBoot和vue-element-template的整合,实现了登录功能。
阅读全文