vue实现多层评论回复
Vue 实现多层评论回复
数据结构设计
使用嵌套结构存储评论数据,每条评论包含 id、content、replies 等字段,replies 为子评论数组。
data() {
return {
comments: [
{
id: 1,
content: "一级评论",
replies: [
{
id: 2,
content: "二级回复",
replies: [
{ id: 3, content: "三级回复", replies: [] }
]
}
]
}
]
}
}
递归组件实现
创建递归组件 Comment.vue,通过 v-for 循环渲染子评论,组件内部调用自身实现嵌套。
<template>
<div class="comment">
<p>{{ comment.content }}</p>
<button @click="replyTo(comment.id)">回复</button>
<div v-if="comment.replies.length" class="replies">
<Comment
v-for="reply in comment.replies"
:key="reply.id"
:comment="reply"
@reply="handleReply"
/>
</div>
</div>
</template>
<script>
export default {
name: 'Comment',
props: ['comment'],
methods: {
handleReply(parentId, content) {
this.$emit('reply', parentId, content)
}
}
}
</script>
添加回复功能
在父组件中实现 addReply 方法,通过递归查找目标评论 ID 并插入新回复。
methods: {
addReply(parentId, content) {
const findAndReply = (comments) => {
for (let comment of comments) {
if (comment.id === parentId) {
comment.replies.push({
id: Date.now(),
content,
replies: []
})
return true
}
if (comment.replies.length && findAndReply(comment.replies)) {
return true
}
}
return false
}
findAndReply(this.comments)
}
}
样式优化
为不同层级评论添加缩进样式,增强视觉层次感。
.comment {
margin-left: 20px;
padding: 10px;
border-left: 2px solid #eee;
}
.replies {
margin-top: 10px;
}
完整调用示例
在父组件中引入并循环顶级评论,传递回复事件。
<template>
<div>
<Comment
v-for="comment in comments"
:key="comment.id"
:comment="comment"
@reply="addReply"
/>
</div>
</template>






