vue实现抖音评论
Vue 实现抖音评论功能
数据结构设计
评论数据通常采用嵌套结构,包含主评论和子评论(回复)。示例数据结构:
comments: [
{
id: 1,
userId: 101,
avatar: 'user1.jpg',
username: '用户A',
content: '这个视频太棒了!',
timestamp: '10分钟前',
likes: 24,
replies: [
{
id: 11,
userId: 102,
avatar: 'user2.jpg',
username: '用户B',
content: '我也觉得',
timestamp: '5分钟前',
likes: 5
}
]
}
]
评论列表渲染
使用 v-for 渲染嵌套评论,通过递归组件处理子评论:
<template>
<div class="comment-list">
<div v-for="comment in comments" :key="comment.id" class="comment-item">
<img :src="comment.avatar" class="avatar">
<div class="content">
<span class="username">{{ comment.username }}</span>
<p>{{ comment.content }}</p>
<div class="meta">
<span>{{ comment.timestamp }}</span>
<button @click="likeComment(comment.id)">赞 {{ comment.likes }}</button>
</div>
<!-- 子评论 -->
<div v-if="comment.replies.length" class="reply-list">
<CommentItem v-for="reply in comment.replies" :comment="reply"/>
</div>
</div>
</div>
</div>
</template>
发表评论功能
实现评论输入框和提交逻辑:
<template>
<div class="comment-input">
<input
v-model="newComment"
placeholder="说点什么..."
@keyup.enter="submitComment"
>
<button @click="submitComment">发送</button>
</div>
</template>
<script>
export default {
data() {
return {
newComment: ''
}
},
methods: {
submitComment() {
if (!this.newComment.trim()) return
const comment = {
id: Date.now(),
userId: currentUserId,
content: this.newComment,
timestamp: '刚刚',
likes: 0,
replies: []
}
this.$emit('add-comment', comment)
this.newComment = ''
}
}
}
</script>
点赞功能实现
为评论添加点赞交互:
methods: {
likeComment(commentId) {
const comment = findCommentById(this.comments, commentId)
if (comment) {
comment.likes += comment.liked ? -1 : 1
comment.liked = !comment.liked
}
}
}
无限滚动加载
结合 IntersectionObserver 实现滚动加载:
mounted() {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.loadMoreComments()
}
})
observer.observe(this.$refs.loadMoreTrigger)
}
样式优化
抖音风格的 CSS 关键点:
.comment-list {
max-height: 60vh;
overflow-y: auto;
scrollbar-width: none; /* 隐藏滚动条 */
}
.comment-item {
display: flex;
padding: 8px 0;
border-bottom: 1px solid #eee;
}
.avatar {
width: 36px;
height: 36px;
border-radius: 50%;
margin-right: 12px;
}
性能优化建议
- 使用虚拟滚动处理大量评论
- 对频繁更新的点赞数使用防抖
- 图片懒加载
- 分页加载评论数据
完整组件示例
<template>
<div class="comment-container">
<CommentInput @add-comment="addComment"/>
<CommentList :comments="comments" @like="handleLike"/>
</div>
</template>
<script>
export default {
data() {
return {
comments: [] // 从API获取初始数据
}
},
methods: {
addComment(comment) {
this.comments.unshift(comment)
},
handleLike(commentId) {
// 更新点赞状态
}
}
}
</script>






