文章目录
👩💻 基础Web开发练手项目系列:个人网站制作
欢迎回到基础Web开发练手项目系列!
在前几篇博文中,我们已经创建了个人网站的基本结构、样式、导航栏、项目展示、联系信息、表单交互、动画效果、页面滚动效果、响应式设计、性能优化、页面动画、用户认证、数据库集成、电子邮件通知、社交媒体集成和博客功能。
在本篇中,我们将学习如何添加用户评论功能,使你的博客更加互动。
🚀 添加用户评论功能
🔨使用MongoDB
🔧步骤 1: 修改博客模型
在 server.js
文件中修改博客模型,添加评论字段:
const blogSchema = new mongoose.Schema({
title: String,
content: String,
author: String,
date: { type: Date, default: Date.now },
comments: [{ body: String, date: { type: Date, default: Date.now } }]
});
const Blog = mongoose.model('Blog', blogSchema);
🔧步骤 2: 添加评论路由
在 server.js
文件中添加评论路由:
// 添加评论
app.post('/blogs/:id/comments', async (req, res) => {
const blogId = req.params.id;
const { body } = req.body;
try {
const blog = await Blog.findById(blogId);
if (!blog) {
return res.status(404).json({ message: '
博客未找到' });
}
// 将评论添加到博客的评论数组中
blog.comments.push({ body });
const updatedBlog = await blog.save();
res.json(updatedBlog);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
🔨使用Vue.js
🔧步骤 3: 渲染评论
在 index.html
文件中渲染评论:
<div id="app">
<h2>博客列表</h2>
<ul>
<li v-for="blog in blogs" :key="blog._id">
{{ blog.title }} - {{ blog.author }}
<ul>
<li v-for="comment in blog.comments" :key="comment.date">
{{ comment.body }}
</li>
</ul>
<input v-model="newComment" placeholder="添加评论">
<button @click="addComment(blog._id)">提交评论</button>
</li>
</ul>
</div>
在 script.js
文件中添加Vue实例中的方法:
const app = new Vue({
el: '#app',
data: {
blogs: [],
newComment: ''
},
mounted() {
// 获取博客数据
this.fetchBlogs();
},
methods: {
fetchBlogs() {
fetch('/blogs')
.then(response => response.json())
.then(data => this.blogs = data)
.catch(error => console.error('获取博客数据失败:', error));
},
addComment(blogId) {
fetch(`/blogs/${blogId}/comments`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ body: this.newComment })
})
.then(response => response.json())
.then(data => {
// 更新本地博客数据
const blogIndex = this.blogs.findIndex(blog => blog._id === blogId);
this.blogs[blogIndex] = data;
// 清空评论输入框
this.newComment = '';
})
.catch(error => console.error('添加评论失败:', error));
}
}
});
🚀 预览与保存
确保保存所有文件并在浏览器中预览你的网站。你现在应该看到一个拥有用户评论功能的更加互动的个人网站了!
🚀 下一步计划
在下一篇文章中,我们将学习如何添加用户权限管理,使你的网站更加安全。记得继续关注本系列,为你的网站增添更多强大的功能!
通过这个项目,你已经学到了Web开发中许多重要的基础知识,并通过添加用户评论功能使你的博客更加生动。祝你编码愉快,不断创新!