【问题标题】:Change Like Button更改喜欢按钮
【发布时间】:2019-11-27 10:22:02
【问题描述】:

我正在使用 Lumen、Vuejs 和 Axios。登录的用户可以发布内容,其他用户可以点赞和评论。我想做的是让人们很明显喜欢这篇文章。但是有人喜欢后我无法切换按钮。

这是我的 Vuejs 代码:

  <button class="btn btn-light" @click="likes(item.id)"><i class="far fa-heart"></i></button>

  <button class="btn btn-light" @click="likes(item.id)"><i class="fas fa-heart"></i></button>

    likes(id){
      const axiosConfig = {
        headers: {
          Authorization: localStorage.getItem('token')
        }
      };
      const postData = {
          posts_id: id,
          likes: true
       };
        axios.post('http://lumen.local/like', postData, axiosConfig)
        .then(response => {
          this.getPosts();
          })
        .catch(error => {
            console.log(error)
          });
    },

这是我的流明代码:

      $post_query = Posts::with('comments')
             ->with('comments.owner')
             ->with('likes.isLiked')
             ->withCount('likes')
             ->where('user_id', $user->id)
             ->orderBy('id', 'desc')
             ->limit($request->limit)
             ->get();

我尝试制作另一个函数,在那里我可以获取登录用户的 user_id,所以我可以使用 vue-if 更改按钮

  public function checkLike(Request $request)
  {
    $user_name= $request->username;
    $user = User::where('username', $user_name)->first();

    $post_id = $request->posts_id;
    $post = Posts::find($post_id);

    $like = Likes::where('posts_id', $post_id)
                    ->where('user_id', $user->id)
                    ->get();

    if(count($like) == 0){
      return response()->json('no likes');
    } else{
      return response()->json($like);
    }

  }

它在邮递员中工作,但我无法在 Vuejs 中实现它,因为我无法在没有 v-for 的情况下获取 user_id。所以我想我应该在posts_query中获取user_id,但我做不到。 你有什么想法吗?

【问题讨论】:

  • 只是为了获得更清晰的信息,您可以复制/粘贴您从后面得到的请求响应吗?可以通过一些 JS 变通方法快速完成
  • cmets: Array(1) content: "thehehe" created_at: (...) id: 829 likes: Array(4) likes_count: 4 updated_at: (...) user_id: 217 这是我从 post_query 得到什么。我想我需要喜欢它的人的 user_id。上面的 user_id 来自发布者。
  • 好的,谢谢,但我想看看你的likes 数组的内容。该数组是否包含有关喜欢该帖子的用户的信息?如果是,并且它实际上为每个用户提供了 id,那么您将能够调整 VueJS 代码以显示您正在寻找的内容!
  • 所以我的喜欢数组看起来像这样: created_at: (...) id: (...) is_liked: (...) likes: (...) posts_id: (... ) updated_at: (...) user_id: 220. user_id 给出了喜欢的人的 id。但是如何在 Vuejs 中编写代码来查找经过身份验证的用户?感谢您的回答。
  • 好的,现在我们接近目标了;如果我了解您的需求,您是否希望有一个按钮可以在当前用户喜欢它时改变其外观?所以基本上,你得到了当前用户的user_id,如果你在按钮的liked数组中找到相同的user_id,那么你就可以使按钮变暗或禁用。我说的对吗?

标签: php laravel vue.js axios lumen


【解决方案1】:

根据您在 cmets 中提供的详细信息,我可以建议您尝试一下。 (我还没有测试过,所以可能有一些语法错误)

在你的 Vue 脚本部分:

data() {
  return {
    currentUserId: null,
    items: null,
  }
},

mounted() {
  this.getCurrentUserId()
  this.getPosts()
},        

methods: {
  getCurrentUserId() {
    // returns the ID of the current user
  },
  likes() {
    // your method
  },
  getPosts() {
    axios.get(MY_URL)
      .then (res => {
        const posts = res.data
        /* 
         *  creates a new array that contains each post + a boolean that indicates if 
         *  the current user has liked or not.
         */
        this.items = posts.map(post => ({
          ...post,
          liked: this.isPostLiked(post.likes)
        }))
      })
      .catch (err => {
        console.error(err)
      })      
  },
  /* 
   *  Not sure if your likes array is composed like this.
   *  This method looks for the currentUserId inside the 
   *  likes array passed as an argument. Returns true when
   *  it finds one, otherwise returns false.
   */
  isPostLiked(likesArray) {
    likesArray.forEach(like => {
      if (like.user_id === this.currentUserId) {
        return true
      }
    }
    return false
  }
},

现在我们应该获得一个对象数组,其中包含每个帖子及其喜欢的状态。

然后您只需在模板中使用v-for 循环遍历它:

<div v-if="items !== null" class="like-buttons">
  <button 
    v-for="(item, index) in items"
    :key="'item_' + index"
    class="btn btn-light"
    @click="likes(item.id)"
  >
    <i v-if="item.liked === true" class="far fa-heart" />
    <i v-else class="fas fa-heart" />
  </button>
</div>

【讨论】:

  • 自从我发布问题以来已经有一段时间了,但我无法查看它。所以我看看,它对我不起作用。我也有一个 getPosts 方法,我想也许这就是问题所在。而且我也不明白地图的方法。
  • 这就是我的 get Posts 方法:getPosts(){ let token = localStorage.getItem('token') this.axios.get(url"+this.$route.params.username, { headers: { 授权:令牌 } }).then(response => { this.posts = response.data; }) .catch(error => { console.log(error) }); }
猜你喜欢
  • 2013-05-23
  • 1970-01-01
  • 1970-01-01
  • 2012-09-20
  • 2012-07-27
  • 2016-04-04
  • 2014-09-21
  • 2019-07-03
  • 2012-02-25
相关资源
最近更新 更多