SpringBoot+Vue 简单小文章项目开发全过程
由于篇幅所限,以下仅展示SpringBoot后端的核心代码和Vue前端的部分代码。
SpringBoot后端核心代码:
@RestController
@RequestMapping("/api/articles")
public class ArticleController {
@Autowired
private ArticleService articleService;
@GetMapping
public ResponseEntity<List<Article>> getAllArticles() {
List<Article> articles = articleService.findAll();
return ResponseEntity.ok(articles);
}
@GetMapping("/{id}")
public ResponseEntity<Article> getArticleById(@PathVariable(value = "id") Long articleId) {
Article article = articleService.findById(articleId);
return ResponseEntity.ok(article);
}
@PostMapping
public ResponseEntity<Article> createArticle(@RequestBody Article article) {
Article newArticle = articleService.save(article);
return ResponseEntity.ok(newArticle);
}
@PutMapping("/{id}")
public ResponseEntity<Article> updateArticle(@PathVariable(value = "id") Long articleId, @RequestBody Article articleDetails) {
Article article = articleService.findById(articleId);
article.setTitle(articleDetails.getTitle());
article.setContent(articleDetails.getContent());
Article updatedArticle = articleService.save(article);
return ResponseEntity.ok(updatedArticle);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteArticle(@PathVariable(value = "id") Long articleId) {
articleService.deleteById(articleId);
return ResponseEntity.noContent().build();
}
}
Vue前端核心代码(使用axios发送请求):
<template>
<div>
<h1>文章列表</h1>
<ul>
<li v-for="article in articles" :key="article.id">
<router-link :to="{ name: 'ArticleDetails', params: { id: article.id }}">{{ article.title }}</router-link>
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
articles: []
};
},
created() {
this.fetchArticles();
},
methods: {
fetchArticles() {
axios.get('/api/articles')
.then(response => {
this.articles = response.data;
})
评论已关闭