Javascript

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

本文主要是介绍Laravel 5.8 做个知乎 12 —— 关注按钮 Vue js的组件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1 创建组件

\resources\js\components\QuestionFollowButton.vue

<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

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>

 

 

 

 

 

这篇关于Laravel 5.8 做个知乎 12 —— 关注按钮 Vue js的组件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!