VUEJS检查用户是否喜欢帖子

时间:2019-09-04 08:54:58

标签: vue.js

我想检查用户是否已经喜欢该帖子。我得到了一个包含喜欢该帖子的用户的数组,但是如果username数组中存在登录的likes,我不知道如何隐藏按钮。这是代码部分:

          <span v-for="like in b.likes">
              {{like}} //  {"username": "Gohanas" } { "username": "Zlotte" }
          </span>

          <button class="likeButton" @click="like(b._id)">LIKE</button>

由于这里存在Zlotte,因此我想隐藏LIKE按钮。我怎样才能做到这一点 ?

2 个答案:

答案 0 :(得分:1)

这里是一个示例,只需将Zlotte替换为当前使用的用户名:

<button
  v-if="!b.likes.find(u => u.username === 'Zlotte')"
  class="likeButton"
  @click="like(b._id)"
>
  LIKE
</button>

答案 1 :(得分:0)

我认为解决此问题的最佳方法是创建一个包含以下代码的计算器:

return b.likes.filter(({ username }) => username === <here the variable for the current username>).length;

更具可读性的变体:

return b.likes.filter((like) => {
    return like.username === <here the variable for the current username>;
}).length;

我不确定b的结构,因此不知道您那里是否有当前用户的姓名。

如果已添加计算值,则可以在模板中使用它来v-ifv-show按钮:

<button class="likeButton" @click="like(b._id)" v-if="<name of the computed here>">LIKE</button>