Vue.js 实现评论回复功能:点击查看单个评论的回复
<template>
<div>
<div v-for="comment in comments" :key="comment.id">
<p>{{ comment.text }}</p>
<button @click="toggleReplies(comment.id)">查看回复</button>
<div v-if="comment.showReplies">
<div v-for="reply in comment.replies" :key="reply.id">
<p>{{ reply.text }}</p>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
comments: [
{
id: 1,
text: '这是评论1',
showReplies: false,
replies: [
{ id: 1, text: '回复1' },
{ id: 2, text: '回复2' }
]
},
{
id: 2,
text: '这是评论2',
showReplies: false,
replies: [
{ id: 1, text: '回复1' },
{ id: 2, text: '回复2' }
]
}
]
};
},
methods: {
toggleReplies(commentId) {
const comment = this.comments.find(comment => comment.id === commentId);
comment.showReplies = !comment.showReplies;
}
}
};
</script>
<p>本示例使用 v-for 循环渲染评论列表。每个评论包含一个文本内容、一个查看回复按钮和一个用于显示回复的区域。</p>
<ul>
<li>点击查看回复按钮会调用 toggleReplies() 方法,该方法找到对应的评论并切换 showReplies 属性,从而控制回复区域的显示与隐藏。</li>
<li>使用 v-if 指令根据 showReplies 的值控制回复区域的显示与隐藏。</li>
<li>使用 v-for 循环渲染每个评论的回复内容。</li>
</ul>
<p><strong>注意:</strong></p>
<p>在实际开发中,你可能需要从后端获取评论数据,并将其存储在 comments 数组中。本示例仅为演示目的,使用了一个硬编码的评论数组。</p>
<p>希望此示例能帮助你理解如何使用 Vue.js 实现评论回复功能。如果你有任何问题或建议,请随时提出。</p>
原文地址: https://www.cveoy.top/t/topic/p4Vu 著作权归作者所有。请勿转载和采集!