用vue写一个修改个人资料的页面,用springboot和mysql获取数据
时间: 2024-02-09 17:10:01 浏览: 23
好的,以下是一个简单的示例代码:
前端Vue代码:
```vue
<template>
<div>
<h1>修改个人资料</h1>
<form>
<div>
<label for="name">姓名:</label>
<input type="text" v-model="name" id="name">
</div>
<div>
<label for="age">年龄:</label>
<input type="number" v-model="age" id="age">
</div>
<div>
<label for="gender">性别:</label>
<select v-model="gender" id="gender">
<option value="男">男</option>
<option value="女">女</option>
</select>
</div>
<button type="submit" @click.prevent="submit">提交</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
name: '',
age: '',
gender: ''
}
},
methods: {
submit() {
// 提交表单数据到后端
axios.post('/api/update', {
name: this.name,
age: this.age,
gender: this.gender
}).then(response => {
console.log(response.data)
}).catch(error => {
console.log(error)
})
}
}
}
</script>
```
后端Spring Boot代码:
```java
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserRepository userRepository;
@PostMapping("/update")
public ResponseEntity<String> updateUser(@RequestBody User user) {
User existingUser = userRepository.findById(user.getId()).orElse(null);
if (existingUser == null) {
return ResponseEntity.notFound().build();
}
existingUser.setName(user.getName());
existingUser.setAge(user.getAge());
existingUser.setGender(user.getGender());
userRepository.save(existingUser);
return ResponseEntity.ok("修改成功");
}
}
```
其中,`User`类是一个简单的实体类,包含`id`、`name`、`age`、`gender`等属性,`UserRepository`是一个JPA接口,继承了`JpaRepository`,用于操作数据库。在这个示例中,我们假设已经完成了数据库的连接和配置。
当用户在前端页面点击“提交”按钮时,会向后端发送一个POST请求,请求的URL为`/api/update`,请求体为一个包含用户信息的JSON对象。后端接收到请求后,会根据请求体中的用户ID查询数据库,找到对应的用户,并将其姓名、年龄、性别等信息更新为请求体中的值。最后,后端返回一个表示操作成功的响应。
这是一个非常简单的示例,实际应用中可能需要进行更多的校验、异常处理等操作。