更改喜欢按钮

时间:2019-07-18 13:08:18

标签: php laravel vue.js axios lumen

我正在使用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,但是我做不到。 你有什么想法吗?

1 个答案:

答案 0 :(得分:0)

根据您在评论中给我的详细信息,我建议您尝试一下。 (我尚未测试过,所以可能是一些语法错误)

在您的Vue脚本部分:

    @Configuration
    public class SimpleTestSecurityConfig extends WebSecurityConfigurerAdapter {

        private String[] PERMIT_ALL = {"unsecured-endpoint1", "unsecured-endpoint2", "..."};

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers(PERMIT_ALL).permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .oauth2Login()
                    .loginPage("/login")
                    .defaultSuccessUrl("/home")
                    .failureUrl("/error")

                    .authorizationEndpoint()
                    .baseUri("/oauth2/authorize-client") //default is "/oauth2/authorization"
                    .and()

                    .tokenEndpoint()
                    .accessTokenResponseClient(accessTokenResponseClient())
                    .and()

                    //.redirectionEndpoint()
                    //.baseUri("/oauth2/redirect") //base for google is "/login/oauth2/code"
                    //.and()

                    .userInfoEndpoint().oidcUserService(new OidcUserService(){
                        @Override
                        public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
                            return super.loadUser(userRequest);
                        }
            });

        }

        @Bean
        public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository(){
            return new HttpSessionOAuth2AuthorizationRequestRepository();
        }


        @Bean
        public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient(){
            return new NimbusAuthorizationCodeTokenResponseClient();
        }

    }

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

然后,您只需要在模板中插入 spring: security: oauth2: client: registration: google: client-id: your-client-id client-secret: your-client-secret redirectUriTemplate: "http://localhost:8080/login/oauth2/code/google" scope: - email - profile 就可以遍历它:

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
  }
},