【问题标题】:Show/hide an element within one list item, not all of them在一个列表项中显示/隐藏一个元素,而不是全部
【发布时间】:2019-08-22 22:54:58
【问题描述】:

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

如何在 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
        }
    }
}

【问题讨论】:

  • 不使用布尔值,而是跟踪应该打开哪个 textarea 的 id,例如 &lt;form v-if="hideReply === comment.data.id"&gt;
  • 抱歉,我对此有点困惑——我还需要添加什么才能使其正常工作?
  • 我只是不知道在 if v-on:click 部分我可以将它链接到评论 ID。
  • 试试 v-on:click="hideReply = comment.data.id"

标签: javascript list vue.js show-hide


【解决方案1】:

在每条评论上添加 show 属性,并使用它来显示/隐藏每条评论

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

相应地更改变量

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

【讨论】:

  • 完成这项工作还需要其他什么吗?如何定义 show 属性?
  • 你应该在 cmets 数组上使用 map this.cmets = cmets.map( item => { item.show = true; return item} )
猜你喜欢
  • 1970-01-01
  • 2012-04-30
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
  • 2021-04-22
  • 1970-01-01
  • 2023-03-22
  • 2016-05-17
相关资源
最近更新 更多