【问题标题】:how to stop iterating my like button inside my post如何停止在我的帖子中迭代我的喜欢按钮
【发布时间】:2020-07-12 15:46:22
【问题描述】:

我正在开发一个带有点赞的帖子系统,用户可以在其中切换帖子,就像我已经正确完成了除了最后一步之外的所有事情,我的 v-for 循环中的问题我从类似帖子的关系中获取点赞表(多对多,因为喜欢表有 user_id 和 post_id),但即使我在这里添加条件,它也在迭代我的按钮 -> duplicated like button,我尝试了很多东西 v-if,v-show 我认为问题出在我的算法我希望有人可以为我解决这个问题,谢谢。

<div class="panel panel-white post panel-shadow" v-for="post in posts" >
            <div class="post-heading">
                <div class="pull-left image">
                    <img v-bind:src="'img/profile/' + post.user.photo" class="img-circle avatar" alt="user profile image">
                </div>
                <div class="pull-left meta">
                    <div class="title h5">
                        <a href="#"><b>{{post.user.name}}  </b></a>

                        made a post.
                    </div>
                    <h6 class="text-muted time">{{post.created_at | hour}}</h6>
                </div>
            </div>
            <div class="post-description">
                <p>{{post.content}}</p>
                <div class="stats">
                       <button class="btn btn-default stat-item"  @click.prevent="addLike(post.id)">
<i class="fa fa-thumbs-o-up" aria-hidden="false" style="color: blue"  v-for="(like) in post.likes" v-bind:style="like.user_id===id && like.post_id===post.id?'color: blue;':'color: gray;'"  > Like &nbsp;{{post.likes.length}}
</i> <!-- here is the duplicate problem-->
                       </button>
                    <a class="btn btn-default stat-item" @click.prevent>
                        <i class="fa fa-reply-all"> {{post.comments.length}}</i> Comments
                    </a>
                </div>
            </div>
            <comment-input :post="post" :userId="id" :userPhoto="userPhoto"></comment-input>
            <ul class="comments-list" v-for="comment in post.comments?post.comments:''">
                <comments :comment="comment" :userId="id" :userPhoto="userPhoto"></comments>
            </ul>
        </div>
        <hr>

    </div>
</div>

【问题讨论】:

    标签: javascript php laravel vue.js v-for


    【解决方案1】:

    不要循环遍历按钮元素,尝试使用likedBythisUser方法来检查当前用户是否喜欢帖子,以便将其绑定到按钮样式:

    methods:{
     likedBythisUser(post,id){
       return post.likes.find(like=>{
              return like.user_id===id && like.post_id===post.id;
    
       }) // return a boolean value 
      }
    
    }
    

    模板:

     <button class="btn btn-default stat-item"  @click.prevent="addLike(post.id)">
    <i class="fa fa-thumbs-o-up" aria-hidden="false" style="color: blue" bind:style="likedBythisUser(post,id)?'color: blue;':'color: gray;'"  > Like &nbsp;{{post.likes.length}}
    </i> <!-- here is the duplicate problem-->
                           </button>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 2019-11-07
      • 2020-08-14
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多