我创建了一个能够收藏帖子的“Like”功能(我知道是因为我在单击“Like”后检查了 DB 中的收藏表)。但是在我点击按钮后,按钮描述保持不变而不是更改为“不喜欢”,即“喜欢”文本在点击按钮后仍然存在。目前,状态/按钮文本仅在我手动重新加载/刷新页面后才会更改。请,我需要帮助以在单击时更改按钮状态,而无需手动刷新页面。非常感谢。
\\
**Model Post.php** -> contains method to check if post is favorited or not
public function favorited()
{
return (bool) Favorite::where('user_id', Auth::id())
->where('post_id', $this->id)
->first();
}
**Model User.php**
public function favorites()
{
return $this->belongsToMany(Post::class, 'favorites', 'user_id',
'post_id')->withTimeStamps();
}
**Controller**
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Post;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
class FavoriteController extends Controller
{
public function __construct(){
$this->middleware('auth');
}
public function store(User $user, $post){
return auth()->user()->favorite_list()->toggle($post->favorites);
}
public function favoritePost(Post $post)
{
Auth::user()->favorites()->attach($post->id);
return back();
}
public function unFavoritePost(Post $post)
{
Auth::user()->favorites()->detach($post->id);
return back();
}
}
**FavoriteButton.Vue Component**
<template>
<span>
<a href="#" v-if="isFavorited" class="btn btn-success" @click.prevent="unFavorite(post)">
Like
</a>
<a href="#" v-else @click.prevent="favorite(post)" class="btn btn-success">
Unlike
</a>
</span>
</template>
<script>
export default {
props: ['post', 'favorited'],
mounted() {
this.isFavorited = this.isFavorite ? true : false;
},
computed: {
isFavorite() {
return this.favorited;
},
},
data: function() {
return {
isFavorited: '',
}
},
methods: {
favorite(post) {
axios.post('/favorite/'+post)
.then(response => this.isFavorited = true)
.catch(response => console.log(response.data));
},
unFavorite(post) {
axios.post('/unfavorite/'+post)
.then(response => this.isFavorited = false)
.catch(response => console.log(response.data));
}
}
}
</script>
**HTML**
@foreach($posts as $post)
<div class="container">
<div style="" class="container">
<h5 style="display: inline">Status: </h5>
<h6 style="display: inline">{{$post->batch_no}}</h6>
</div>
<favorite-button
:post="{{ $post->id }}"
:favorited="{{ $post->favorited() ? 'true' : 'false' }}"
></favorite-button>
</div>
@endforeach
\\