首页 > 解决方案 > 在一个列表项中显示/隐藏一个元素,而不是全部

问题描述

我已经在 Vue 中的服务器上生成了一个动态评论列表,现在希望在每条评论上出现一个“回复”按钮,单击该按钮会在其下方打开一个文本区域并链接到该评论。然而,我的 hacky 解决方案意味着点击它会打开所有评论的文本框,而不仅仅是一个。

如何使用 Vue 中的显示/隐藏功能单独定位每个评论?

我知道为什么我的解决方案不起作用——但我不知道从哪里开始创建一个针对单击它的特定评论的功能。

模板 (HTML)

<ul>
    <li v-for="comment in comments" :key="comment.data.id">
        <div>User details</div>
        <div>Comment content</div>
        <div>
            <span>
                <a v-on:click="hideReply = !hideReply">Reply</a>
            </span>
        </div>

        <form v-if="hideReply">
            <textarea>Reply text box</textarea>
            <button>Reply button</button>
        </form>
    </li>
    <li>Another comment in the list...</li>
    <li>Another comment in the list...</li>
    ...
</ul>

脚本 (JS)

export default {
    name: 'Post',
    components: {},
    data () {
        return{
            hideReply: false,
            comment: undefined,
            comments: undefined
        }
    },
    async created () {
        // code to bring in my comments from server
    },
    methods: {
        betterShowHideFunction () {
            // where do i start
        }
    }
}

标签: javascriptlistvue.jsshow-hide

解决方案


在每个评论上添加一个显示属性,并使用它来显示/隐藏每个单独的评论

<form v-if="comment.show">

相应地更改 var

<a v-on:click="comment.show = !comment.show">Reply</a>

推荐阅读