Vue.js 实现评论回复功能:点击查看隐藏的回复
你可以通过使用 v-for 循环来显示评论列表,并为每个评论添加一个点击事件,以便显示或隐藏该评论的回复。
首先,在你的数据中添加一个属性,用于表示每个评论是否显示回复。例如,你可以在每个评论对象中添加一个名为'showReply'的属性,初始值为 false。
data() {
return {
comments: [
{ id: 1, content: '评论1', showReply: false, replies: [] },
{ id: 2, content: '评论2', showReply: false, replies: [] },
{ id: 3, content: '评论3', showReply: false, replies: [] },
],
};
},
然后,在模板中使用 v-for 循环来显示评论列表,并为每个评论添加一个点击事件,以切换显示或隐藏该评论的回复。
<template>
<div>
<div v-for="comment in comments" :key="comment.id">
<p>{{ comment.content }}</p>
<button @click="toggleReply(comment)">查看回复</button>
<div v-if="comment.showReply">
<div v-for="reply in comment.replies" :key="reply.id">
<p>{{ reply.content }}</p>
</div>
</div>
</div>
</div>
</template>
最后,在方法中实现 toggleReply 方法,用于切换评论的 showReply 属性的值。
methods: {
toggleReply(comment) {
comment.showReply = !comment.showReply;
},
},
这样,当你点击'查看回复'按钮时,就会切换该评论的 showReply 属性的值,从而显示或隐藏该评论的回复。
原文地址: https://www.cveoy.top/t/topic/p4Uy 著作权归作者所有。请勿转载和采集!