php - 更改喜欢按钮
问题描述
我正在使用 Lumen、Vuejs 和 Axios。登录的用户可以发布内容,其他用户可以点赞和评论。我想做的是让人们很明显喜欢这篇文章。但是有人喜欢后我无法切换按钮。
这是我的 Vuejs 代码:
<button class="btn btn-light" @click="likes(item.id)"><i class="far fa-heart"></i></button>
<button class="btn btn-light" @click="likes(item.id)"><i class="fas fa-heart"></i></button>
likes(id){
const axiosConfig = {
headers: {
Authorization: localStorage.getItem('token')
}
};
const postData = {
posts_id: id,
likes: true
};
axios.post('http://lumen.local/like', postData, axiosConfig)
.then(response => {
this.getPosts();
})
.catch(error => {
console.log(error)
});
},
这是我的流明代码:
$post_query = Posts::with('comments')
->with('comments.owner')
->with('likes.isLiked')
->withCount('likes')
->where('user_id', $user->id)
->orderBy('id', 'desc')
->limit($request->limit)
->get();
我尝试制作另一个函数,在那里我可以获取登录用户的 user_id,所以我可以使用 vue-if 更改按钮
public function checkLike(Request $request)
{
$user_name= $request->username;
$user = User::where('username', $user_name)->first();
$post_id = $request->posts_id;
$post = Posts::find($post_id);
$like = Likes::where('posts_id', $post_id)
->where('user_id', $user->id)
->get();
if(count($like) == 0){
return response()->json('no likes');
} else{
return response()->json($like);
}
}
它在邮递员中工作,但我无法在 Vuejs 中实现它,因为没有 v-for 就无法获取 user_id。所以我想我应该在posts_query中获取user_id,但我做不到。你有什么想法?
解决方案
根据您在评论中给我的详细信息,我可以建议您尝试一下。(我还没有测试过,所以可能有一些语法错误)
在您的 Vue 脚本部分:
data() {
return {
currentUserId: null,
items: null,
}
},
mounted() {
this.getCurrentUserId()
this.getPosts()
},
methods: {
getCurrentUserId() {
// returns the ID of the current user
},
likes() {
// your method
},
getPosts() {
axios.get(MY_URL)
.then (res => {
const posts = res.data
/*
* creates a new array that contains each post + a boolean that indicates if
* the current user has liked or not.
*/
this.items = posts.map(post => ({
...post,
liked: this.isPostLiked(post.likes)
}))
})
.catch (err => {
console.error(err)
})
},
/*
* Not sure if your likes array is composed like this.
* This method looks for the currentUserId inside the
* likes array passed as an argument. Returns true when
* it finds one, otherwise returns false.
*/
isPostLiked(likesArray) {
likesArray.forEach(like => {
if (like.user_id === this.currentUserId) {
return true
}
}
return false
}
},
现在我们应该获得一个对象数组,其中包含每个帖子及其喜欢的状态。
然后你只需要v-for
在你的模板中循环遍历它:
<div v-if="items !== null" class="like-buttons">
<button
v-for="(item, index) in items"
:key="'item_' + index"
class="btn btn-light"
@click="likes(item.id)"
>
<i v-if="item.liked === true" class="far fa-heart" />
<i v-else class="fas fa-heart" />
</button>
</div>
推荐阅读
- ionic-framework - Play商店上传失败
- javascript - 如何使用节点 js 在 mongodb 中增加值
- c# - C# 在两个不同的 Windows 窗体之间使用互斥锁有条件地执行方法
- android - android回收器中的适配器未连接错误
- bash - 使用 Seq 和变量遍历列表
- vue.js - 组件中的 Vue i10n
- github - AWS CloudFormation CodePipeline:无法从 GitHub 获取存储库的内容
- wso2 - WSO2 API Manager 2.1 升级到 2.6
- android - Firebase 取消链接不会完全取消链接 Facebook 提供商
- amazon-web-services - 使用自定义文件夹而不是 ~/.aws