> 文章列表 > Spring boot+Vue博客平台:文章列表展示、文章分类与标签管理模块实现

Spring boot+Vue博客平台:文章列表展示、文章分类与标签管理模块实现

Spring boot+Vue博客平台:文章列表展示、文章分类与标签管理模块实现

本文将详细介绍如何实现博客平台中的文章列表展示、文章分类与标签管理功能,包括前端的Vue组件设计和后端的Spring Boot接口实现。在阅读本文后,您将了解如何设计和实现高效、易用的文章列表展示、文章分类与标签管理功能。

一、文章列表展示

1.设计思路

在设计文章列表展示功能时,我们需要关注以下几点:

  • 支持分页功能,避免一次性加载过多数据
  • 提供文章预览,包括标题、摘要、作者、发布时间等信息
  • 支持按分类和标签筛选文章列表
  • 提供搜索功能,方便用户快速找到感兴趣的文章

2.技术实现

(1) 创建文章列表组件

在前端,使用Vue框架创建一个文章列表组件。该组件包括一个文章列表,每个文章项包含标题、摘要、作者、发布时间等信息。用户可以点击文章标题跳转到文章详情页。

<template><div class="article-list"><div class="article-item" v-for="article in articles" :key="article.id"><h3><router-link :to="{ name: 'article-detail', params: { articleId: article.id } }">{{ article.title }}</router-link></h3><p class="meta">By {{ article.author }} | {{ article.createdAt }}</p><p class="excerpt">{{ article.excerpt }}</p></div><pagination @page-changed="fetchArticles" :total-pages="totalPages" /></div>
</template><script>
export default {data() {return {articles: [],totalPages: 0,};},async created() {await this.fetchArticles(1);},methods: {async fetchArticles(page) {const { data } = await this.$http.get(`/articles?page=${page}`);this.articles = data.content;this.totalPages = data.totalPages;},},
};
</script>

(2) 实现文章列表接口

在后端,使用Spring Boot创建一个处理文章列表请求的接口。根据请求参数,获取指定页码的文章列表,并返回给前端。

@RestController
@RequestMapping("/articles")
public class ArticleController {@Autowiredprivate ArticleRepository articleRepository;@GetMappingpublic ResponseEntity<?> getArticles(@RequestParam(defaultValue = "1") int page) {Pageable pageable = PageRequest.of(page - 1, 10, Sort.by(Sort.Direction.DESC, "createdAt"));Page<Article> articles = articleRepository.findAll(pageable);return ResponseEntity.ok(articles);}
}

二、文章分类与标签管理

1.设计思路

在设计文章分类与标签管理功能时,我们需要关注以下几点:

  • 支持用户自定义分类与标签
  • 支持为文章添加多个分类与标签
  • 支持按分类与标签筛选文章列表

2.技术实现

(1) 创建分类与标签管理组件

在前端,使用Vue框架创建一个分类与标签管理组件。该组件包括分类列表和标签列表,用户可以添加、删除和修改分类与标签。

<template><div class="category-tag-management"><div class="categories"><h3>Categories</h3><ul><li v-for="category in categories" :key="category.id">{{ category.name }}<button @click="deleteCategory(category.id)">Delete</button></li></ul><form @submit.prevent="addCategory"><input type="text" v-model="newCategory" placeholder="Add category" required /><button type="submit">Add</button></form></div><div class="tags"><h3>Tags</h3><ul><li v-for="tag in tags" :key="tag.id">{{ tag.name }}<button @click="deleteTag(tag.id)">Delete</button></li></ul><form @submit.prevent="addTag"><input type="text" v-model="newTag" placeholder="Add tag" required /><button type="submit">Add</button></form></div></div>
</template><script>
export default {data() {return {categories: [],tags: [],newCategory: "",newTag: "",};},async created() {await this.fetchCategoriesAndTags();},methods: {async fetchCategoriesAndTags() {const [categories, tags] = await Promise.all([this.$http.get("/categories"),this.$http.get("/tags"),]);this.categories = categories.data;this.tags = tags.data;},async addCategory() {await this.$http.post("/categories", { name: this.newCategory });this.newCategory = "";await this.fetchCategoriesAndTags();},async deleteCategory(categoryId) {await this.$http.delete(`/categories/${categoryId}`);await this.fetchCategoriesAndTags();},async addTag() {await this.$http.post("/tags", { name: this.newTag });this.newTag = "";await this.fetchCategoriesAndTags();},async deleteTag(tagId) {await this.$http.delete(`/tags/${tagId}`);await this.fetchCategoriesAndTags();},},
};
</script>

(2) 实现分类与标签管理接口

在后端,使用Spring Boot创建一个处理分类与标签管理请求的接口。提供添加、删除和获取分类与标签的接口.

@RestController
@RequestMapping("/api/categories")
public class CategoryController {@Autowiredprivate CategoryRepository categoryRepository;@PostMappingpublic ResponseEntity<?> createCategory(@Valid @RequestBody Category category) {categoryRepository.save(category);return ResponseEntity.status(HttpStatus.CREATED).body("Category created successfully.");}@GetMappingpublic ResponseEntity<?> getCategories() {List<Category> categories = categoryRepository.findAll();return ResponseEntity.ok(categories);}@DeleteMapping("/{categoryId}")public ResponseEntity<?> deleteCategory(@PathVariable Long categoryId) {categoryRepository.deleteById(categoryId);return ResponseEntity.ok("Category deleted successfully.");}
}@RestController
@RequestMapping("/api/tags")
public class TagController {@Autowiredprivate TagRepository tagRepository;@PostMappingpublic ResponseEntity<?> createTag(@Valid @RequestBody Tag tag) {tagRepository.save(tag);return ResponseEntity.status(HttpStatus.CREATED).body("Tag created successfully.");}@GetMappingpublic ResponseEntity<?> getTags() {List<Tag> tags = tagRepository.findAll();return ResponseEntity.ok(tags);}@DeleteMapping("/{tagId}")public ResponseEntity<?> deleteTag(@PathVariable Long tagId) {tagRepository.deleteById(tagId);return ResponseEntity.ok("Tag deleted successfully.");}
}

通过上述代码,我们实现了分类与标签管理接口。现在,用户可以通过这些接口来创建、获取和删除分类与标签。在实际项目中,还可以根据需要添加更多的分类与标签管理功能,例如修改分类与标签、按照分类或标签筛选文章等。

在这里,我们将补充修改分类与标签功能,并介绍如何按分类或标签筛选文章。

一、修改分类与标签功能

1.前端修改功能实现

在分类与标签管理组件中添加一个修改按钮,点击后弹出一个对话框让用户输入新的分类或标签名称。提交后,调用相应的修改接口。

<!-- 修改分类对话框 -->
<template><div class="edit-dialog"><div class="dialog-mask" @click="$emit('close')"></div><div class="dialog-content"><h3>Edit Category</h3><form @submit.prevent="editCategory"><input type="text" v-model="newName" placeholder="Enter new name" required /><button type="submit">Save</button></form></div></div>
</template><script>
export default {props: ['categoryId'],data() {return {newName: "",};},methods: {async editCategory() {await this.$http.put(`/api/categories/${this.categoryId}`, { name: this.newName });this.newName = "";this.$emit('close');this.$emit('updated');},},
};
</script>

2.后端修改功能实现

CategoryControllerTagController中添加修改分类和标签的接口。

// CategoryController
@PutMapping("/{categoryId}")
public ResponseEntity<?> updateCategory(@PathVariable Long categoryId, @Valid @RequestBody Category newCategory) {Optional<Category> optionalCategory = categoryRepository.findById(categoryId);if (optionalCategory.isPresent()) {Category category = optionalCategory.get();category.setName(newCategory.getName());categoryRepository.save(category);return ResponseEntity.ok("Category updated successfully.");} else {return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Category not found.");}
}// TagController
@PutMapping("/{tagId}")
public ResponseEntity<?> updateTag(@PathVariable Long tagId, @Valid @RequestBody Tag newTag) {Optional<Tag> optionalTag = tagRepository.findById(tagId);if (optionalTag.isPresent()) {Tag tag = optionalTag.get();tag.setName(newTag.getName());tagRepository.save(tag);return ResponseEntity.ok("Tag updated successfully.");} else {return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Tag not found.");}
}