Vue.js 使用 v-for 循环评论并控制评论框显示隐藏
<template>
<div>
<div v-for='(comment, index) in comments' :key='index'>
<p>{{ comment.text }}</p>
<button @click='toggleReplyBox(comment)'>回复</button>
<div v-if='comment.showReplyBox'>
<input type='text' v-model='comment.reply' />
<button @click='submitReply(comment)'>提交</button>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
comments: [
{ text: '评论1', showReplyBox: false, reply: '' },
{ text: '评论2', showReplyBox: false, reply: '' },
{ text: '评论3', showReplyBox: false, reply: '' },
],
};
},
methods: {
toggleReplyBox(comment) {
comment.showReplyBox = !comment.showReplyBox;
},
submitReply(comment) {
// 处理回复提交的逻辑
console.log(comment.reply);
comment.reply = '';
comment.showReplyBox = false;
},
},
};
</script>
<p>在上述示例中,<code>comments</code>数组为评论数据对象数组,其中每个评论对象都有一个<code>showReplyBox</code>属性,用于控制评论框的显示与隐藏。通过点击<code>回复</code>按钮,调用<code>toggleReplyBox</code>方法来切换<code>showReplyBox</code>属性的值。在评论框中,通过<code>v-if</code>指令根据<code>showReplyBox</code>属性的值决定是否显示评论框。点击<code>提交</code>按钮后,调用<code>submitReply</code>方法处理回复提交的逻辑,然后将<code>showReplyBox</code>属性设置为<code>false</code>,隐藏评论框。</p>
原文地址: https://www.cveoy.top/t/topic/p4U0 著作权归作者所有。请勿转载和采集!