Laravel 5.8 做个知乎 12 —— 关注按钮 Vue js的组件

1 创建组件

\resources\js\components\QuestionFollowButton.vue

Laravel 5.8 做个知乎 12 ——  关注按钮  Vue js的组件
<template>
    <button class="btn  "
            v-text="text"
            v-on:click="follow"
            v-bind:class="{'btn-success':followed,'btn-info':!followed}">
    </button>
</template>

<script>
    export default {
        name: "QuestionFollowButton",
        props:['question','user'],
        mounted(){
           
            axios.post('/api/question/follower',{'question':this.question,'user':this.user}).then(res => {
                this.followed = res.data.followed;
                //console.log(res.data)
            })
        },
        data(){
            return {
                followed:false
            }
        },
        computed:{
            text(){
                return this.followed ? '已关注':'关注该问题'
            }
        },
        
        methods:{
            follow(){
                //alert('Hello')
               axios.post('/api/question/follow',{'question':this.question,'user':this.user}).then(res => {
                    this.followed = res.data.followed;
                    //console.log(res.data)
                })
            }
        }
    }
</script>

<style scoped>

</style>
View Code

2 加载组件

\resources\js\app.js

//注册组件
Vue.component('question-follow-button', require('./components/QuestionFollowButton'));

3 添加接口

\routes\api.php

Laravel 5.8 做个知乎 12 ——  关注按钮  Vue js的组件
Route::post('/question/follower',function (Request $request){
    //request('question')  或者这样获取
    $followed = !! \App\Follow::where('question_id',$request->get('question'))
                            ->where('user_id',$request->get('user'))
                            ->count();
    return response()->json(['followed'=>$followed]);
})->middleware('api');


Route::post('/question/follow',function (Request $request){
    //判断是否本人
    //,,,
    $followed =  \App\Follow::where('question_id',$request->get('question'))
      ->where('user_id',$request->get('user'))
      ->first();
    
    if ($followed !== null){
        $rs = $followed->delete();
        if ($rs){
            return response()->json(['followed'=>false]);
        }else{
            return response()->json(['error'=>'请稍后再试']);
        }
    }
    $attributes = [
      'question_id'=> $request->get('question'),
      'user_id'    => $request->get('user')
    ];
    
    \App\Follow::create($attributes);
    return response()->json(['followed'=>true]);
})->middleware('api');
View Code

4 使用组件

<question-follow-button question="{{$question->id}}" user="{{Auth::id()}}"></question-follow-button>

 

 

 

 

 

上一篇:vue elementui 复选框实现单选效果


下一篇:Improving Question Answering with External Knowledge