vue实现多层评论回复
Vue 实现多层评论回复
数据结构设计
多层评论通常采用嵌套结构,每个评论对象包含子评论数组。示例数据结构如下:
comments: [
{
id: 1,
content: '父评论',
replies: [
{
id: 3,
content: '子评论',
replies: [] // 可继续嵌套
}
]
}
]
递归组件实现
创建递归组件Comment.vue,通过v-for循环渲染嵌套结构:

<template>
<div class="comment">
<div>{{ comment.content }}</div>
<button @click="replyTo(comment)">回复</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: {
replyTo(comment) {
this.$emit('reply', comment)
},
handleReply(parentComment, content) {
// 处理回复逻辑
}
}
}
</script>
添加回复功能
在父组件中维护评论数据,并提供回复方法:

methods: {
addReply(parentId, content) {
// 递归查找父评论
const findParent = (comments) => {
for (let comment of comments) {
if (comment.id === parentId) {
comment.replies.push({
id: Date.now(),
content,
replies: []
})
return true
}
if (comment.replies && findParent(comment.replies)) {
return true
}
}
return false
}
findParent(this.comments)
}
}
样式优化
为嵌套评论添加缩进效果:
.comment {
margin-left: 20px;
border-left: 1px solid #eee;
padding-left: 10px;
}
.replies {
margin-top: 10px;
}
完整示例调用
主组件调用示例:
<template>
<div>
<Comment
v-for="comment in comments"
:key="comment.id"
:comment="comment"
@reply="handleReply"
/>
<div v-if="replyingTo">
<textarea v-model="replyContent"></textarea>
<button @click="submitReply">提交</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
replyingTo: null,
replyContent: ''
}
},
methods: {
handleReply(comment) {
this.replyingTo = comment.id
},
submitReply() {
this.addReply(this.replyingTo, this.replyContent)
this.replyingTo = null
this.replyContent = ''
}
}
}
</script>





