Vue.js v-for 循环用户评论,点击查看回复,只显示当前评论的回复
<template>
<div>
<div v-for="(comment, index) in comments" :key="index">
<p>{{ comment.text }}</p>
<button @click="showReply(index)">查看回复</button>
<div v-if="comment.showReply">
<p v-for="(reply, replyIndex) in comment.replies" :key="replyIndex">
{{ reply.text }}
</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
comments: [
{
text: '评论1',
showReply: false,
replies: [
{
text: '回复1'
},
{
text: '回复2'
}
]
},
{
text: '评论2',
showReply: false,
replies: [
{
text: '回复3'
},
{
text: '回复4'
}
]
}
]
}
},
methods: {
showReply(index) {
this.comments[index].showReply = !this.comments[index].showReply;
}
}
}
</script>
<p>该代码使用 Vue.js 的 v-for 循环遍历用户评论数组 <code>comments</code>。在每个评论中,使用 <code>v-if</code> 指令控制回复内容的显示与隐藏。点击“查看回复”按钮时,会调用 <code>showReply</code> 方法,切换当前评论的 <code>showReply</code> 状态,实现动态显示回复内容。</p>
<p><strong>具体步骤:</strong></p>
<ol>
<li><strong>定义评论数据</strong>: 在 <code>data</code> 中定义 <code>comments</code> 数组,包含用户评论和对应的回复。</li>
<li><strong>循环遍历</strong>: 使用 <code>v-for</code> 循环遍历 <code>comments</code> 数组,显示每个评论。</li>
<li><strong>添加按钮</strong>: 在每个评论中添加一个按钮,绑定 <code>@click</code> 事件,调用 <code>showReply</code> 方法。</li>
<li><strong>显示回复</strong>: 使用 <code>v-if</code> 指令判断 <code>showReply</code> 状态,决定是否显示当前评论的回复。</li>
<li><strong>切换显示</strong>: <code>showReply</code> 方法通过修改当前评论的 <code>showReply</code> 状态来切换回复的显示与隐藏。</li>
</ol>
<p>该方法可以有效地展示用户评论及其回复,提高用户体验。</p>
原文地址: https://www.cveoy.top/t/topic/p4Vo 著作权归作者所有。请勿转载和采集!