1 创建组件
esourcesjscomponentsQuestionFollowButton.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>
2 加载组件
esourcesjsapp.js
//注册组件 Vue.component('question-follow-button', require('./components/QuestionFollowButton'));
3 添加接口
outesapi.php
Route::post('/question/follower',function (Request $request){
//request('question') 或者这样获取
$followed = !! AppFollow::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 = AppFollow::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')
];
AppFollow::create($attributes);
return response()->json(['followed'=>true]);
})->middleware('api');
4 使用组件
<question-follow-button question="{{$question->id}}" user="{{Auth::id()}}"></question-follow-button>