Vue 实现头条评论
Vue 实现头条评论功能
数据准备与绑定
使用 Vue 的 data 或 ref(Composition API)存储评论列表和用户输入内容。例如:
data() {
return {
comments: [
{ id: 1, content: "第一条评论", likes: 10 },
{ id: 2, content: "第二条评论", likes: 5 }
],
newComment: ""
}
}
模板渲染
通过 v-for 渲染评论列表,结合 v-model 绑定输入框:
<div v-for="comment in comments" :key="comment.id">
<p>{{ comment.content }}</p>
<button @click="likeComment(comment.id)">点赞 {{ comment.likes }}</button>
</div>
<input v-model="newComment" placeholder="输入评论">
<button @click="addComment">提交</button>
交互逻辑 实现添加评论和点赞功能的方法:

methods: {
addComment() {
if (this.newComment.trim()) {
this.comments.push({
id: Date.now(),
content: this.newComment,
likes: 0
});
this.newComment = "";
}
},
likeComment(id) {
const comment = this.comments.find(c => c.id === id);
if (comment) comment.likes++;
}
}
优化与扩展功能
分页加载
结合 axios 实现分页请求,监听滚动事件加载更多:
async loadMore() {
const res = await axios.get('/api/comments', { params: { page: this.page } });
this.comments = [...this.comments, ...res.data];
this.page++;
}
用户认证 在提交评论时检查登录状态:

addComment() {
if (!this.$store.state.isLoggedIn) {
alert("请先登录");
return;
}
// 原有逻辑
}
样式与交互增强
悬浮效果 使用 CSS 增强交互体验:
.comment-item:hover {
background-color: #f5f5f5;
transition: background 0.3s;
}
时间格式化 显示评论发布时间,使用过滤器或计算属性:
filters: {
formatDate(value) {
return new Date(value).toLocaleString();
}
}
模板中调用:
<span>{{ comment.time | formatDate }}</span>






