基于vue和elementui、axios、和springboot写一个评论区的模块,有点赞数+评论
时间: 2024-06-09 14:06:25 浏览: 109
基于vue+vue-router+vuex+element-ui+axios,参考小米商城,实现的电商项目,仿小米商城源代码
5星 · 资源好评率100%
好的,下面是一个简单的实现过程。
前端部分:
1. 使用 Vue CLI 创建一个新项目,然后安装 Element UI、Axios 和 Vue Router。
```
vue create my-project
cd my-project
npm install element-ui axios vue-router --save
```
2. 在 `src` 目录下创建一个 `views` 文件夹,里面放置一个 `Comment.vue` 组件。
```vue
<template>
<div>
<div class="comment-header">
<h3>评论</h3>
<el-button type="primary" @click="showForm = true">添加评论</el-button>
</div>
<div class="comment-body">
<el-card v-for="comment in comments" :key="comment.id">
<div class="comment-info">
<span class="comment-author">{{ comment.author }}</span>
<span class="comment-date">{{ comment.date }}</span>
</div>
<div class="comment-content">{{ comment.content }}</div>
<div class="comment-actions">
<el-button size="small" type="text" @click="editComment(comment)">编辑</el-button>
<el-button size="small" type="text" @click="deleteComment(comment)">删除</el-button>
<el-button size="small" type="text" @click="likeComment(comment)">
{{ comment.likes }} <i class="el-icon-thumb-up"></i>
</el-button>
</div>
</el-card>
</div>
<el-dialog title="添加评论" :visible.sync="showForm" width="50%" center>
<el-form :model="newComment" label-width="80px">
<el-form-item label="用户名">
<el-input v-model="newComment.author"></el-input>
</el-form-item>
<el-form-item label="评论内容">
<el-input type="textarea" v-model="newComment.content"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="showForm = false">取消</el-button>
<el-button type="primary" @click="addComment">确定</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'Comment',
data() {
return {
comments: [],
showForm: false,
newComment: {
author: '',
content: ''
}
};
},
methods: {
fetchComments() {
axios.get('/api/comments').then(response => {
this.comments = response.data;
}).catch(error => {
console.log(error);
});
},
addComment() {
axios.post('/api/comments', this.newComment).then(response => {
this.comments.push(response.data);
this.newComment.author = '';
this.newComment.content = '';
this.showForm = false;
}).catch(error => {
console.log(error);
});
},
editComment(comment) {
// TODO
},
deleteComment(comment) {
axios.delete(`/api/comments/${comment.id}`).then(response => {
const index = this.comments.indexOf(comment);
this.comments.splice(index, 1);
}).catch(error => {
console.log(error);
});
},
likeComment(comment) {
axios.post(`/api/comments/${comment.id}/like`).then(response => {
comment.likes = response.data.likes;
}).catch(error => {
console.log(error);
});
}
},
mounted() {
this.fetchComments();
}
};
</script>
<style scoped>
.comment-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
}
.comment-info {
display: flex;
justify-content: space-between;
margin-bottom: 8px;
}
.comment-author {
font-weight: bold;
}
.comment-date {
color: #999;
}
.comment-content {
margin-bottom: 8px;
}
.comment-actions {
display: flex;
justify-content: flex-end;
}
</style>
```
3. 在 `src` 目录下创建一个 `router` 文件夹,里面放置一个 `index.js` 路由配置文件。
```js
import Vue from 'vue';
import VueRouter from 'vue-router';
import Comment from '@/views/Comment.vue';
Vue.use(VueRouter);
const routes = [
{
path: '/',
name: 'Comment',
component: Comment
}
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
});
export default router;
```
4. 在 `src` 目录下创建一个 `main.js` 入口文件,里面配置 Axios 和 Element UI。
```js
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import axios from 'axios';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.config.productionTip = false;
axios.defaults.baseURL = 'http://localhost:8080';
Vue.prototype.$http = axios;
Vue.use(ElementUI);
new Vue({
router,
render: h => h(App)
}).$mount('#app');
```
5. 创建一个 `public` 文件夹,里面放置一个 `index.html` 文件,用于渲染 Vue 应用。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Project</title>
</head>
<body>
<div id="app"></div>
<script src="/dist/js/chunk-vendors.js"></script>
<script src="/dist/js/app.js"></script>
</body>
</html>
```
后端部分:
1. 使用 Spring Initializr 创建一个新项目,然后添加 Spring Web、Spring Data JPA 和 H2 Database 的依赖。
2. 在 `src/main/java` 目录下创建一个 `com.example.myproject` 包,里面放置一个 `MyProjectApplication.java` 入口文件。
```java
package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyProjectApplication {
public static void main(String[] args) {
SpringApplication.run(MyProjectApplication.class, args);
}
}
```
3. 在 `src/main/java` 目录下创建一个 `com.example.myproject.controller` 包,里面放置一个 `CommentController.java` 控制器,用于处理评论相关的 API 请求。
```java
package com.example.myproject.controller;
import com.example.myproject.entity.Comment;
import com.example.myproject.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.transaction.Transactional;
import java.util.List;
@RestController
@RequestMapping("/api/comments")
public class CommentController {
@Autowired
private CommentRepository commentRepository;
@GetMapping
public List<Comment> getAllComments() {
return commentRepository.findAll();
}
@PostMapping
public Comment createComment(@RequestBody Comment comment) {
return commentRepository.save(comment);
}
@PutMapping("/{id}")
public ResponseEntity<Comment> updateComment(@PathVariable Long id, @RequestBody Comment comment) {
Comment existingComment = commentRepository.findById(id).orElse(null);
if (existingComment == null) {
return ResponseEntity.notFound().build();
}
existingComment.setAuthor(comment.getAuthor());
existingComment.setContent(comment.getContent());
Comment updatedComment = commentRepository.save(existingComment);
return ResponseEntity.ok(updatedComment);
}
@DeleteMapping("/{id}")
public ResponseEntity<Comment> deleteComment(@PathVariable Long id) {
Comment comment = commentRepository.findById(id).orElse(null);
if (comment == null) {
return ResponseEntity.notFound().build();
}
commentRepository.delete(comment);
return ResponseEntity.ok(comment);
}
@Transactional
@PostMapping("/{id}/like")
public ResponseEntity<Comment> likeComment(@PathVariable Long id) {
Comment comment = commentRepository.findById(id).orElse(null);
if (comment == null) {
return ResponseEntity.notFound().build();
}
comment.setLikes(comment.getLikes() + 1);
Comment updatedComment = commentRepository.save(comment);
return ResponseEntity.ok(updatedComment);
}
}
```
4. 在 `src/main/java` 目录下创建一个 `com.example.myproject.entity` 包,里面放置一个 `Comment.java` 实体类,用于表示评论。
```java
package com.example.myproject.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String author;
private String content;
private Integer likes = 0;
private Date date = new Date();
public Comment() {}
public Comment(String author, String content) {
this.author = author;
this.content = content;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getLikes() {
return likes;
}
public void setLikes(Integer likes) {
this.likes = likes;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
```
5. 在 `src/main/java` 目录下创建一个 `com.example.myproject.repository` 包,里面放置一个 `CommentRepository.java` 接口,用于与数据库交互。
```java
package com.example.myproject.repository;
import com.example.myproject.entity.Comment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CommentRepository extends JpaRepository<Comment, Long> {
}
```
6. 在 `src/main/resources` 目录下创建一个 `application.properties` 配置文件,用于配置 H2 Database。
```
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
```
7. 运行项目,访问 `http://localhost:8080/h2-console` 可以进入 H2 Database 控制台,查看评论表的数据。
8. 运行项目,访问 `http://localhost:8080/` 可以进入 Vue 应用,查看评论区的界面效果。
以上就是一个简单的基于 Vue 和 Spring Boot 的评论区模块的实现过程。
阅读全文