Laravel技巧集锦(34):使用vuejs组件化开发点赞按钮

准备:原理类似关注作者 https://blog.csdn.net/sinat_37390744/article/details/89363482

1、api.php

Route::post('/answer/{id}/votes/users','VotesController@users');
Route::post('/answer/vote','VotesController@vote')

2、controller

public function users($id){
        $user = \Auth::guard('api')->user();
        if ($user->hasVotedFor($id)){ //判断用户是否点赞
            return response()->json(['voted'=>true]);
        }
        return response()->json(['voted'=>false]);

 }

 public function vote(){


        $answer = $this->answer->byId(\request('answer'));


        $voted = \Auth::guard('api')->user()->voteFor(\request('answer'));



        if(count($voted['attached'])>0){


            $answer->increment('votes_count');
            return response()->json(['voted'=>true]);
        }


        $answer->decrement('votes_count');
        return response()->json(['voted'=>false]);

    }

3、vue

<template>

    <button  class="btn  btn-default ufbtn"
             v-bind:class="{'btn-success':followed}"
             v-text="text"
             v-on:click="follow"

    >


    </button>
</template>

<script>
    export default {

        props:['user'],

        mounted() {

            this.$http.get('/api/user/followers/' + this.user).then(response=>{
                this.followed = response.data.followed;
            });
        },

        data(){
            return {
                followed:false
            }
        },

        computed:{
            text(){
                return this.followed?'已关注':'关注TA';
            }
        },

        methods:{
            follow() {
                this.$http.post('/api/user/follow',{'user':this.user}).then(response=>{
                    this.followed = response.data.followed;

                    console.log(response.data.followed);
                });
            },
        }
    }
</script>

4、注册vue

5、引入vue

6、user.php

public function votes(){
        return $this->belongsToMany(Answer::class,'votes')->withTimestamps();
    }

    public function voteFor($answer){
        return $this->votes()->toggle($answer);
    }

    public function hasVotedFor($answer){
        return !!$this->votes()->where('answer_id',$answer)->count();
    }

7、userrepository.php

class UserRepository
{
    public function byId($id){
        return \App\User::find($id);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值