vue3加springboot实现登录注册功能
时间: 2023-11-09 17:04:41 浏览: 56
要实现Vue3和Spring Boot的登录注册功能,可以按照以下步骤进行:
1. 创建Vue3项目
首先需要创建Vue3项目。可以使用Vue CLI工具快速创建一个Vue3项目:
```bash
vue create my-project
```
2. 创建Spring Boot项目
使用Spring Initializr创建Spring Boot项目。选择依赖包,可以选择Web、JPA、MySQL等。
3. 创建数据库表
在MySQL数据库中创建用户表,包括用户名和密码等字段。
4. 实现后端接口
编写Spring Boot的Controller类,实现登录和注册的接口。在Controller类中,可以使用Spring Security实现用户认证和授权。
5. 实现前端页面
在Vue3项目中,使用Vue Router实现页面的跳转。在组件中,使用axios库发送Ajax请求,调用后端接口实现登录和注册功能。
6. 测试运行
启动Spring Boot项目和Vue3项目,测试登录和注册功能是否正常。
示例代码:
Spring Boot后端代码:
```java
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public String login(@RequestBody User user) {
boolean result = userService.login(user.getUsername(), user.getPassword());
if (result) {
return "success";
} else {
return "fail";
}
}
@PostMapping("/register")
public String register(@RequestBody User user) {
userService.register(user);
return "success";
}
}
```
Vue3前端代码:
```vue
<template>
<div>
<form>
<div>
<label>用户名:</label>
<input type="text" v-model="username">
</div>
<div>
<label>密码:</label>
<input type="password" v-model="password">
</div>
<button @click.prevent="login">登录</button>
<button @click.prevent="register">注册</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
username: '',
password: ''
}
},
methods: {
login() {
axios.post('/login', {
username: this.username,
password: this.password
}).then(response => {
if (response.data === 'success') {
// 登录成功,跳转到首页
this.$router.push('/');
} else {
alert('登录失败');
}
});
},
register() {
axios.post('/register', {
username: this.username,
password: this.password
}).then(response => {
if (response.data === 'success') {
alert('注册成功');
}
});
}
}
}
</script>
```
注意:
1. 在后端接口中使用@RequestBody注解接收前端传递的JSON对象。
2. 在前端页面中使用v-model指令实现数据的双向绑定。
3. 在axios库中使用post方法发送Ajax请求。
4. 在Vue Router中使用$route.push方法实现页面的跳转。